This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Best way to split a String on it's Capitals Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Best way to split a String on it Watch "Best way to split a String on it New topic
Author

Best way to split a String on it's Capitals

Paul Duer
Ranch Hand

Joined: Oct 10, 2002
Posts: 98
Hi guys,
I just wrote a method that takes a string with no spaces, and puts spaces before any capital letter. The end goal is to take strings like ("IceCream") and get back ("Ice Cream"), notice that I trim the first Space back off, don't need it.
Okay, so here's my code below. I wanted to know if there is any faster or less code lines way to do the same thing:
public String getProgramSpaceName() {
StringBuffer workingProgramID = new StringBuffer(programID);
StringBuffer finalProgramID = new StringBuffer();
for(int x=0; x<workingProgramID.length(); x++) {
char checkChar = workingProgramID.charAt(x);
if (Character.isUpperCase(checkChar)) {
finalProgramID.append(" " + checkChar);
} else {
finalProgramID.append(checkChar);
}
}
return finalProgramID.toString().trim();
}
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817


Not much different from your code, but it takes fewer lines of code and would be slightly more efficient. (Note that you do not need your workingProgramID variable)


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Philip Shanks
Ranch Hand

Joined: Oct 15, 2002
Posts: 189
Okay, I'll bite... as a Perl hacker my first inclination is to seek a regex based solution. The java.util.regex package isn't quite as easy to use as Perl's built in functionality, but this isn't too tough:

As we say, TMTOWTDI ("There's more than one way to do it").


Philip Shanks, SCJP - Castro Valley, CA
My boss never outsources or has lay-offs, and He's always hiring. I work for Jesus! Prepare your resume!
Paul Duer
Ranch Hand

Joined: Oct 10, 2002
Posts: 98
Thank you both for your thoughtful answers, I plan to try them both! I like the simplicity and attention to detail in both, I am glad to have the second opinions.
I think a lot of times as programers we forget to see how others might solve the same problem. It's a ashame because I think we could write much better together. Like a big programming love in!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Best way to split a String on it's Capitals
 
Similar Threads
Strings
how to trim a StringBuffer??!!
What's special about StringBuffer ?
Integer.parseInt : NumberFormatException
select element as parameter for query