I need help with replacing segments of a string in Java.
I have tried both the String method 'replace' and StringTokenizer. As the segments of my strings is of unknown length I guess StringTokeniz开发者_运维技巧er is out of question. I also need to go through several strings (with many similar segments to replace in each string). I have assumed there is a command for finding substrings something like "begin with..., and end with..." but have not found any.
As I am new to programming, this case might be simple for all but me...
Thanks in advance!
You couldn't find any methods to find substrings or Strings that begin with or end with certain Strings? Where did you look?
There are various replace methods in the String class:
alt text http://img14.imageshack.us/img14/8811/picture2pg.png
But it might be really inefficient if you are doing a lot of replaces, as each time a new string is constructed. Instead the StringBuilder class works perfectly for that case:
alt text http://img16.imageshack.us/img16/1667/picture1knk.png
Try string.replaceAll
or string.replaceFirst
, which allow you to carry out the replacement based on a regular expression.
String.replaceAll(regex, replacement)
Regex can be just about everything.
精彩评论