Java, how to read each character in a string?

Associate
Joined
21 May 2003
Posts
1,008
Hi. I'm trying to make a program which has two arguments. the first is a flag (-u, -l, or -t) and the second is a string. the flag says wether to make it upper case, lower case, or title case.

Here's the code i've done so far:


*********************************************************
class Case
{
public static void main (String[] args)
{
String tag;
String text;
Case program = new Case();
if (args.length != 2)
{
System.err.println ("Invalid");
System.exit(1);
}
tag = args[0];
text = args[1];

if(tag.equals("-u"))
{
System.out.println(text.toUpperCase());
}
else if(tag.equals("-l"))
{
System.out.println(text.toLowerCase());
}
else if(tag.equals("-t"))
{
program.titlecase(text);
}
else
{
System.err.println ("Invalid");
System.exit(1);
}

}

void titlecase (String text)
{

}
}

*********************************************************


The problem is, when i send the text to title case, it's still as a string. to make it title case, i need to read every character, and make every character after a white space a capital.



I was thinking to make it an array but i don't know how to convert from a string to an array. Or maybe i could make it an array from the very beginning and use loops to capitalise and lowerise(!). but how?

EDIT: for osme reason *** code isn't keeping its indentation.
 
Associate
Joined
25 Jul 2003
Posts
1,980
Well like everyone else you seem to not know how to use the java api:
http://java.sun.com/j2se/1.5.0/docs/api/

A 10 second scan down the String class in the API shows:

toCharArray()
Converts this string to a new character array.

which is probably a sensible place to start if you want to do it that way.


To do what you want you will probably find this method more useful:

String[] split(String regex)
Splits this string around matches of the given regular expression.

If you make the regex so that the String[] is essentially the array of words in the sentence you can then go and just capitalize the first letter of each one, then join the strings back together again.


ps: use [ CODE ] tags to keep indentation when posting stuff :):

Code:
...
    indentation
         rar
...
 
Last edited:
Associate
Joined
3 Dec 2003
Posts
943
i would tokenize the string ( seperate it into words) everytime you read the token you set the first character to uppercase, then reform the string by adding white spaces between the tokens, maybe you can use regular expression
 
Back
Top Bottom