Java Trying a String exercise in JAva

AI Thread Summary
The discussion focuses on a coding issue related to capitalizing the first letter of each word in a sentence. The initial code provided fails to modify the string as intended because the `toUpperCase` method does not change the original character but returns a new one. A suggested correction involves appending the capitalized first character to a new string, followed by the rest of the word. The revised code correctly implements this approach by first converting the first character to uppercase, then appending the remaining characters of the word, and finally adding a space. The conversation also touches on the efficiency of this method and whether there are simpler alternatives for achieving the same result.
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;

	}
 
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top