Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 724
  • Last Modified:

Title Case

i want to read in a string and output it in title case (so every capital after a space (of a few spaces) will be capitalised.

obviously to do this i'll have to change the string into an array of chars, but i'm not sure how to capitalise then, since:

   char stringinput[] = input.toCharArray();
   stringinput[0] = stringinput[0].toUpperCase();

doesn't seem to work.

that code there is just to capitalise the 1st letter, but i'm not sure how to do this
0
Gesus
Asked:
Gesus
  • 2
1 Solution
 
vemulCommented:
try this..

          String c = String.valueOf(input.charAt(0)).toUpperCase();
          String output = c + input.substring(1);
0
 
GesusAuthor Commented:
i used


// prints input in title case
 void title(String input)
 {
  int len;
  int i;
  input = input.toLowerCase();
  len = input.length();
  char stringinput[] = input.toCharArray();
  stringinput[0] = Character.toUpperCase(stringinput[0]);
  for (i=0; i+1!= len ;i++)
  {
   if (stringinput[i]==' ')
   {
    stringinput[i+1]=Character.toUpperCase(stringinput[i+1]);
   }
  }
  String output = new String(stringinput);
  System.out.println (output);
 }
0
 
vemulCommented:
yes, that should also work.. did u have any problems with it?
0
 
jam40jeffCommented:
Your code looks like it should work unless the string ends with a space character.  Your loop should begin with

for(i = 0; i < len - 1; i++)

so that it does not test the last character.  If it tests the last character (i = len - 1) and this character is equal to ' ', then stringinput[i + 1] will throw a NullPointerException.

Otherwise, the code looks like it should work perfectly.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now