Trying a String exercise in JAva

  • Context: Java 
  • Thread starter Thread starter camel-man
  • Start date Start date
  • Tags Tags
    Exercise Java String
Click For Summary
SUMMARY

The discussion focuses on capitalizing the first letter of each word in a sentence using Java. The initial code fails to modify the string as the Character.toUpperCase method does not change the original character but returns a new one. The corrected approach involves storing the uppercase character in a temporary variable and then appending it to the result string. The final implementation effectively capitalizes the first letter of each word while preserving the rest of the word.

PREREQUISITES
  • Understanding of Java programming language
  • Familiarity with string manipulation in Java
  • Knowledge of Java methods and return values
  • Basic understanding of loops and conditionals in Java
NEXT STEPS
  • Explore Java StringBuilder for more efficient string concatenation
  • Learn about Java Streams for functional-style string manipulation
  • Investigate regular expressions in Java for advanced string processing
  • Study Java's String.format method for formatted output
USEFUL FOR

Java developers, software engineers, and anyone interested in string manipulation techniques in Java programming.

camel-man
Messages
76
Reaction score
0
I am trying to capitalize the first letter of every word in a sentence.
Example. "hey what's up" would be "Hey What's Up".

here is my code but nothing is changing the sentence. I thought everything was right.

Code:
	public static String cap(String aString) {

		String[] sentence = aString.split(" ");
		String b = "";
		for (int i = 0; i < sentence.length; i++) {
			Character.toUpperCase(sentence[i].charAt(0));
			b += sentence[i] + " ";
		}

		return b;

	}
 
Technology news on Phys.org
The toUpperCase method doesn't change the parameter you pass to it. It returns the converted character.

So you want to do something like
Code:
b += Character.toUpperCase(sentence[i].charAt(0));
and then append the rest of the "word" to b.
 
Thank you for the tip. So does this suffice? How bad is it and are there easier ways to accomplish this?

Code:
public static String cap(String aString) {

		String[] sentence = aString.split(" ");
		String b = "";
		for (int i = 0; i < sentence.length; i++) {
			char temp = Character.toUpperCase(sentence[i].charAt(0));
			b += temp;
			for(int j = 1; j<sentence[i].length(); j++)
				b += sentence[i].charAt(j);
			
			b += " ";
		}

		return b;

	}
 

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
8
Views
3K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 1 ·
Replies
1
Views
1K
Replies
1
Views
2K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 1 ·
Replies
1
Views
4K
Replies
55
Views
7K
  • · Replies 3 ·
Replies
3
Views
1K