Skip to content

Commit

Permalink
feat: Add method for capitalize first letter of each word from string
Browse files Browse the repository at this point in the history
  • Loading branch information
Vishwajeet-29-pro committed Dec 6, 2024
1 parent c2fdfba commit 6fe2f0a
Showing 1 changed file with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package org.practice.dsa.strings;

public class CapitalizeFirstChar {
public static void main(String[] args) {
System.out.println(capitalize("hello world"));
System.out.println(capitalizeEach("hello world"));
}

// only first letter of first word
public static String capitalize(String str) {
if (str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}

// first letter of all words
public static String capitalizeEach(String str) {
if (str.isEmpty()) {
return str;
}
String[] words = str.split(" ");
StringBuilder result = new StringBuilder();
for (String word: words) {
if (!word.isEmpty()) {
result.append(word.substring(0, 1).toUpperCase())
.append(word.substring(1))
.append(" ");
}
}
return result.toString().trim();
}
}

0 comments on commit 6fe2f0a

Please sign in to comment.