0

I've searched for a bit on this forum and all I can seem to find are questions on how to make the first letter of every word uppercase. Which is not what I'm looking for.

I'm looking for something that will check through all of the words in the String, and if they're uppercase, will change the letters to lowercase EXCEPT for the first one.

Like, let's say the string is:

"HI STACKOVERFLOW"

It would change it to:

"Hi Stackoverflow"

Or:

"I'M ASKING A QUESTION ON stackoverflow dot com"

It would change it to:

"I'm Asking a Question On stackoverflow dot com"

3 Answers3

4

I would use the StringTokenizer class to break the string up into the separate words. Then you can get each token as a separate String and compare:

String line = "A BIG Thing that Something"

StringTokenizer st = new StringTokenizer(line);

        while(st.hasMoreTokens)
            {
                String a = st.nextToken();
                if(a.equals(a.toUpperCase())){
                    System.out.println(a.charAt(0) + a.substring(1).toLowerCase());
                }else{
                    System.out.println(a);
                    }
            }

Something like that... You'll need to remember to import StringTokenizer, it's part of the java.util package.

noMAD
  • 7,744
  • 19
  • 56
  • 94
Sekm
  • 1,658
  • 13
  • 22
  • what does `if(a.equals(a.toUpperCase())` do? Just change the token to Upper Case? In that case, why do you need the `if()`? – noMAD Apr 23 '12 at 04:17
  • that part checks if a is equal to itself in uppercase (i.e. if a is uppercase). The if is because the poster wanted to make those types of tokens only have a leading capital, the else if to keep everything else the same. Does that make sense? – Sekm Apr 23 '12 at 04:20
  • Thanks guys, do you know how I'd be able to make it so that if the first letter is a symbol (ie. ":") it wouldn't lowercase the second character. So people would be able to do :D and not have it go to :d? – Cody Thompson Apr 23 '12 at 04:41
  • 1
    @CodyThompson: You will have to add more conditions with `a.charAt(0)`. Check ASCII table to see what to compare. I am not giving you the answer because `learning by searching >>>> asking` ;-) – noMAD Apr 23 '12 at 05:05
1
   public static void main(String[] args) {
      String org= "HI STACKOVERFLOW";
      String [] temp=org.split(" ");
      int len=temp.length;
      String ne = ".";
      for(int i=0;i<len;i++)
      {

         temp[i]=temp[i].toUpperCase();
         temp[i]=(temp[i].substring(0, 1)).toUpperCase()+(temp[i].substring(1, temp[i].length())).toLowerCase();
        System.out.print(temp[i]+" "); 
      }

    }

output Hi Stackoverflow

Lijo
  • 6,498
  • 5
  • 49
  • 60
-1

If you're open to incorporate a library in your project, I'm quite sure that Apache Commons-lang StringUtils has the type of functionality you need.