Trying a String exercise in JAva

  • Context: Java 
  • Thread starter Thread starter camel-man
  • Start date Start date
  • Tags Tags
    Exercise Java String
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 2K views
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;

	}
 
Physics 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;

	}