GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Converting a String to Proper Case Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting a String to Proper Case" Watch "Converting a String to Proper Case" New topic
Author

Converting a String to Proper Case

Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
Hi all,

This is my second post for help on this site, and I am frantic! I can't find anywhere how to convert a string object to proper case. how would you convert, say, a variable called myWord to proper case? I know how to convert it to upper and lower case, but I cannot find anything to convert to proper case.

I know this is very beginner-ish, but hey, I'm a beginner!!

Thanks for any help!!
Amy
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi Amy,

Don't act too frantic or you might make the Moose stampede. Trust me, you don't want that to happen.

Proper case, meaning MyWord or Myword? Or something else? This isn't really something common enough to warrant a member function in String; it's something you have to cadge together yourself.

One way to do it would look something like this:

1. Create a StringBuffer "b".
2. Use the charAt() method of String to get the first character.
3. Use the static toUpperCase() method of Character to capitalize this character.
4. Append the capitalized character to "b".
5. Use the substring() method of String to get a String consisting of every character but the first from the original String.
6. Append this new String to "b".
7. Use the toString() method of StringBuffer to get the new, capitalized String.

If you want only the first letter capitalized, just use toLowerCase() on the String from step 5.


[Jess in Action][AskingGoodQuestions]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I'd step back even further than EFH describes above (although he somewhat hinted at my suggestions that follow). As EFH, changing a String to "proper case" is not a common task. In fact, I'm not even sure what you mean by "proper case". So the first thing is to define what this means. If you can explain it to us in English, maybe it will give you some ideas about how to get started writing a method that does this. From there, you can use some of EFH's suggestions above.

Layne


Java API Documentation
The Java Tutorial
Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
Hi again,

Sorry for not being clear on it. EFH was right above; it is when the first letter is capitalized and the rest are lower case, also referred to as initial caps. I am still working on it. I know it is not a common task, as it is hard to find informaiton out there!!

Thanks,
Amy
James Carman
Ranch Hand

Joined: Feb 20, 2001
Posts: 580
You might want to check out the StringUtils and WordUtils classes from the Jakarta Commons Lang project. They might help you do what you want. If nothing else, you can download the code to see how they do it and maybe adapt it to your situation. That's what open source is all about.


James Carman, President<br />Carman Consulting, Inc.
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Initial Letter Of What Though?
In English the initial letter of some words like the name of a city (say London) are capitalised but most are not unless they're the first letter in a sentence. Then again sometimes a word may be capitalised in places where it normally would not be, like people referring to London as 'the City'.


42
Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
OK,

Here is what I am trying to do. I am passing a String variable, call it myWord, to a setProper method. This variable is passed to it in all uppercase letters. What I need to do is to convert the word passed in, call it JACKET, to proper case, namely Jacket. I have that part down now (thanks EFH!!)

Now, what I am trying to do is to jazz it up a little and pass a String variable with several words in it, and capitalize the first letter of every part of it. I am using the StringTokenizer to do this.

So, say an input variable is passed in as 123 CHERRY STREET, it has to be converted to 123 Cherry Street. All I am doing is calling the setProper method (mentioned above) every time a new token is found.

What I haven't figured out yet is how to send just that one token to the setProper method. I can send the whole String, but obviously that doesn't do me much good in this case, as all it is doing is capitalizing the '1'. Here is my code for that method:

StringBuffer output = new StringBuffer();
String dataHolder;

StringTokenizer tokens = new StringTokenizer(input, " ");
while (tokens.hasMoreTokens()) {
dataHolder = Customer.setProper(input); // this is where it is wrong
output.append(dataHolder);
tokens.nextToken();
}

return output.toString();


How do I just pass the one token to the setProper method instead of the whole input String? I have a test in the main method to see if 123 CHERRY STREET is equal to 123 Cherry Street at the end. Right now, the output buffer contains this: 123 cherry street123 cherry street123 cherry street. I just need to get it to perform the setProper method on each of the tokens individually instead of the input String three times. I tried dataHolder = Customer.setProper(tokens.nextToken("")) but that doesn't work. Do I need a different delimiter?

Thanks for any help! Sorry this is so small in the scope of Java...
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

All she wants is a String to be Proper Case. Proper Case is defined as the first letter of a word is capitalized, nothing more or less. No need to read further into the definition.

You guys sometimes make me laugh when you over analyze a question.

Personally, I'd get the first Letter, capitalize it. Get the rest and lower case them, then combine them together. Unless Jakarta COmmans already has a class and method to do that for you.

Mark


Perfect World Programming, LLC - Two Laptop Bag - Tube Organizer
How to Ask Questions the Smart Way FAQ
Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
Thank you Mark! I just posted again so I think everything should be OK and (hopefully) clear now. Thanks everyone - sorry if I wasn't explaining it correctly.
K Riaz
Ranch Hand

Joined: Jan 08, 2005
Posts: 375
How lazy can some programmers get? Its a 2 minute job in writing the code. Not everything is in the API! What next, a method to return true if integer x is more than integer y?
Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
I'm sorry if this is adolescent for you, but that is why I am posting to the beginner forum. I am a beginner; about 2-3 months into trying to teach myself Java with only 1 school semester of C++ before this. I am stuck on this one piece though and that is why I am asking for help. I just can't figure out quite how the statement is supposed to look, or what the syntax would be, and what the delmiter should be (if any).

Thanks,
Amy
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Kashif, we'd appreciate if you remember this is supposed to be a friendly place. For beginners, and everyone else. Thank you.


"I'm not back." - Bill Harding, Twister
Horatio Westock
Ranch Hand

Joined: Feb 23, 2005
Posts: 221
Originally posted by Kashif Riaz:
How lazy can some programmers get? Its a 2 minute job in writing the code. Not everything is in the API! What next, a method to return true if integer x is more than integer y?


Remember that we are in the beginner forum of JavaRanch "a friendly place for Java greenhorns"!!
K Riaz
Ranch Hand

Joined: Jan 08, 2005
Posts: 375
I was refering to Mark Spritzler's reference as to whether a commons.lang package existed which could do the work, not the thread-starter.
Horatio Westock
Ranch Hand

Joined: Feb 23, 2005
Posts: 221


The call tokens.nextToken() returns the next token as a string, so if you change setProper(input) to setProper( tokens.nextToken() ), you should get the results you expect.



You could also do this using the split method of the String class if you are using 1.4 or above:



Hope this helps.
Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
It really does, thanks so much for your reply. I'm grasping at straws here.

I tried this before; here is what my statement looks like:

while
...
dataHolder = setProper( tokens.nextToken() );
...

I also tried one with the class name on it:

dataHolder = Customer.setProper( tokens.nextToken() );

And I get these errors (at runtime) every time:

java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java.232)
at com.lexx.ecommerce.Customer.setProperEachWord(Customer.java:73)
at com.lexx.ecommerce.Customer.main(Customer.java:44)

The setProperEachWord method is just calling the setProper method to convert each token to proper case. Any ideas?? Am I not importing something (I am importing java.util.StringTokenizer but that is all). Thanks so much! I really, really appreciate your reply.
Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
Nevermind; I had an extra token.nextToken() statement in there. Sorry! I have one small issue to deal with yet (putting spaces back in to the String) but I'll do some searching. Thanks so much for replying! I really really appreciate it and my brain needed it! Woo Hoo! I wouldn't have figured it out without looking back at your code and noticing that the dataHolder = setProper(tokens.nextToken() ) statement was the only one in there.

Thanks so much!
Horatio Westock
Ranch Hand

Joined: Feb 23, 2005
Posts: 221
Originally posted by Amy Caine:
I have one small issue to deal with yet (putting spaces back in to the String) but I'll do some searching.


This should be quite simple hopefully. All you need to do is add a line:



in your loop after you append the modified word. Watch out though, you might not want to do this after the last word in the sentence. If you want to avoid that, you can use the hasMoreTokens() check again within your loop to see if you are on the last one:

Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Amy Caine:
Now, what I am trying to do is to jazz it up a little and pass a String variable with several words in it, and capitalize the first letter of every part of it. I am using the StringTokenizer to do this.

It sounds like you've made some progress recently. However, I'd like to make a suggestion. To me, this begs to be split into two different methods: one that changes a single word to proper case and another that parses a String with multiple words. The later method can call the first method on each String.

Even though this may be a beginning assignment, I feel that it is good to start learning techniques to organize your code now so that you can learn good habits for when you start working on more complicated projects. In this case, since you are performing two separate tasks (even if they are realated), they can be implemented in two separate methods.

Layne
Amy Caine
Ranch Hand

Joined: Jan 29, 2005
Posts: 30
Thank you Horatio! I did put code in to just append that space character in there. I didn�t think about doing the tokens.hasMoreTokens() check again though. All I did was append a space every time, then send the buffer value back trimmed: return output.toString().trim();. That worked, but I will do it this way instead because I like it; it really makes sense.

Layne, thank you for the suggestion! I really appreciate it when someone makes suggestions as to how things can be more efficient and coded more effectively. In my case, I have a setProper() method, then there is a setProperEachWord() method that calls the setProper() method for each token in the string. Is this what you are referring to?

One more scenario � how do you pass an instance of Customer to another method? Everything I�m reading says treat it as a variable, but I am getting static errors. I may have it set up wrong.

What I am trying to do is this; I have a string that is divided into 6 parts; first name, last name, address, city, state and zip. For each token I am calling a populateCustomer() method that defines what part of the string it is by taking the field number (ie case 0 = first name, case 1 = last name, etc. I have a counter in the while loop to determine this). It then sends this data to the setProperEachWord() method (see above) to change it to proper case. At the end, I want to return the whole thing after all of the parts of the string have gone through this process. But I need to account for if the file has more than one record. How does this work? I have a counter for the fields, but what happens when that record is processed and there is another one? How do I advance another counter to say that hey, there is more than one instance of cust so I have to change my value from 1 to 2?

So my questions are these; how does Java handle more than one record? Is it just that the hasMoreTokens() is true until the end of the file instead of the end of one record? If so, how do you differentiate between one instance and another? If not, how do you get Java to advance to the next instance?

Thanks, again, for helping a mere greenhorn try and get these concepts down.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

Originally posted by Kashif Riaz:
How lazy can some programmers get? Its a 2 minute job in writing the code. Not everything is in the API! What next, a method to return true if integer x is more than integer y?


I'm not writing the code. And yes there is a method to return an int if x is more than y. Integer implements the Comparable interface whihc has the comparTo method which returns a positive 1 if x is greater than y.

Mark
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Layne, thank you for the suggestion! I really appreciate it when someone makes suggestions as to how things can be more efficient and coded more effectively. In my case, I have a setProper() method, then there is a setProperEachWord() method that calls the setProper() method for each token in the string. Is this what you are referring to?


Yes, that's exactly what I was referring to. I apologize if I missed this detail in the code you posted earlier.


One more scenario � how do you pass an instance of Customer to another method? Everything I�m reading says treat it as a variable, but I am getting static errors. I may have it set up wrong.

While the description you gave above helps us understand what you are *trying* to do, however it's even more helpful if you post the exact code that gives the error as well. You should also post the EXACT error message. This will include a line number indicating where the error occurs. Please indicate which line this refers to since I don't usually have enough time to count them to find it myself

What I am trying to do is this; I have a string that is divided into 6 parts; first name, last name, address, city, state and zip. For each token I am calling a populateCustomer() method that defines what part of the string it is by taking the field number (ie case 0 = first name, case 1 = last name, etc. I have a counter in the while loop to determine this). It then sends this data to the setProperEachWord() method (see above) to change it to proper case.


I assume that the ultimate goal here is to create Customer objects for each of the records in the file. In that case, I would take a very different approach than what you describe here. In words, I would do something like this:

1) gather all the data for a single customer
2) convert any fields to proper case that need it
3) create a Customer object for the gathered data
4) repeat steps 1 through 3 for each record in the file

It sounds like you have a pretty good handle on steps 1 and 2. The only thing I would add here is that you may want to create a variable for each piece of information that you need to obtain in step 1, rather than using a single variable over and over. Step 3 might cause you a little bit of trouble if you are unfamiliar with constructors. A constructor is very similar to a method with the same name as the class it belongs to. In fact, I think of them as a special kind of method even though this is not technically correct. For example, for your Customer class, you can do something like this:

Notice that the constructor does not have a return type. This is one of the distinctions it has from an ordinary method. A constructor can have parameters, like a method, but I thought I'd start simple. However, this has a drawback because the member fields cannot be initialized unless you provide some default value. I won't get into this any further since in this case it will be easier to add parameters to our constructor. If you want to learn more about member fields and default values for them, I'll let you research that on your own.

So let's add some parameters to our constructor:

With this constructor, you can now do step 3 in our description above fairly easily:

Here I'm assuming that two String variables (firstNameToken and lastNameToken) were declared earlier and have been filled in with the correct information from the file (as described in steps 1 and 2 above).

That's all there is to it! Of course, there are more than one way to accomplish the task at hand. There is rarely ever a "best" way. There are typically both pros and cons for using a particular technique. In my experience, what I've described here follows the Object-Oriented Programming paradigm. If it confuses you too much, you are probably best advised to stick with the way you are doing it. I'll make the adjustment to help you along that path.

In any case, I hope this helps some. Let us know what you come up against next.

Keep Coding!

Layne
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Originally posted by Mark Spritzler:
All she wants is a String to be Proper Case. Proper Case is defined as the first letter of a word is capitalized, nothing more or less. No need to read further into the definition.

You guys sometimes make me laugh when you over analyze a question.
Mark


Remember that not everyone has English as their native language (oh how I love to catch one of you at that ).
"proper" in my definition means "whatever it should be to be syntactically and gramatically correct", not "capitalise every first letter".
What that would be depends on the individual words as well as on the language that the OP wants to deal with.
Mark Spritzler
ranger
Sheriff

Joined: Feb 05, 2001
Posts: 17250
    
    6

Originally posted by Jeroen Wenting:


Remember that not everyone has English as their native language (oh how I love to catch one of you at that ).
"proper" in my definition means "whatever it should be to be syntactically and gramatically correct", not "capitalise every first letter".
What that would be depends on the individual words as well as on the language that the OP wants to deal with.


And that's why some people names are all lower case here.

Mark
James Carman
Ranch Hand

Joined: Feb 20, 2001
Posts: 580
Originally posted by Kashif Riaz:
I was refering to Mark Spritzler's reference as to whether a commons.lang package existed which could do the work, not the thread-starter.


Actually, it was me who originally brought up Jakarta Commons Lang. And, the WordUtils.capitalizeFully() method will do exactly what they are looking to do. So, there's no need to write it!
Srijani Ghosh
Greenhorn

Joined: Oct 11, 2013
Posts: 2
you may use the following process , i.e. using regex as follows-

String[] splited = result.split("\\s+");
String[] splited1 = new String[splited.length];

for (int i = 0; i < splited.length; i++) {
int l = splited[i].length();
result1 = "";
for (int j = 0; j < splited[i].length(); j++) {
String next = splited[i].substring(j, j + 1);

if (j == 0) {
result1 += next.toUpperCase();
} else {
result1 += next.toLowerCase();
}
}
splited1[i] = result1;
}
result = "";
for (int i = 0; i < splited1.length; i++) {
result += " " + splited1[i];
}
For more details , please refer to this post -
http://javacodingtutorial.blogspot.com/2013/10/converting-any-string-to-camel-case.html
Richard Tookey
Ranch Hand

Joined: Aug 27, 2012
Posts: 1064
    
  10

Srijani Ghosh wrote:you may use the following process , i.e. using regex as follows-


I suspect the OP has long since moved on from this obvious homework. If I were to use regular expressions for this I would use the Rewriter class available from elliotth.blogspot.co.uk .

Edit : Derived Rewriter class

and use
Ivan Jozsef Balazs
Rancher

Joined: May 22, 2012
Posts: 867
    
    5
James Carman wrote:If nothing else, you can download the code to see how they do it and maybe adapt it to your situation. That's what open source is all about.


Well, in this certainly yes, but not forcibly in the case of, say, Linux. Though open source, it is not likely you'll want to download and peruse the (whole) source...

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Converting a String to Proper Case