-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Add method for capitalize first letter of each word from string
- Loading branch information
1 parent
c2fdfba
commit 6fe2f0a
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
33 changes: 33 additions & 0 deletions
33
JavaDsaWithTest/src/main/java/org/practice/dsa/strings/CapitalizeFirstChar.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |