• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Converting a String to Proper Case

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Amy Caine
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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'.
 
Amy Caine
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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...
 
ranger
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Amy Caine
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Kashif, we'd appreciate if you remember this is supposed to be a friendly place. For beginners, and everyone else. Thank you.
 
Ranch Hand
Posts: 221
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 375
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 221
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


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
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 221
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 3061
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 5093
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 17347
11
Mac IntelliJ IDE Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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!
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Bartender
Posts: 1166
17
Netbeans IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
 
Rancher
Posts: 1044
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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...

 
Liar, liar, pants on fire! refreshing plug:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic