File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best way to split a String on it's Capitals

 
Paul Duer
Ranch Hand
Posts: 98
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1824
Eclipse IDE Java Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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)
 
Philip Shanks
Ranch Hand
Posts: 189
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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").
 
Paul Duer
Ranch Hand
Posts: 98
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic