Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Trying a String exercise in JAva

  1. Sep 7, 2014 #1
    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 (Text):
        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;

        }
     
  2. jcsd
  3. Sep 7, 2014 #2

    AlephZero

    User Avatar
    Science Advisor
    Homework Helper

    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 (Text):

    b += Character.toUpperCase(sentence[i].charAt(0));
     
    and then append the rest of the "word" to b.
     
  4. Sep 7, 2014 #3
    Thank you for the tip. So does this suffice? How bad is it and are there easier ways to accomplish this?

    Code (Text):
    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;

        }
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Trying a String exercise in JAva
Loading...