File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
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

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 {
return finalProgramID.toString().trim();
Joel McNary

Joined: Aug 20, 2001
Posts: 1824

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:
subject: Best way to split a String on it's Capitals
It's not a secret anymore!