views:

135

answers:

4

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 StringTokenizer 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!

+1  A: 

Try string.replaceAll or string.replaceFirst, which allow you to carry out the replacement based on a regular expression.

David M
I´ll try this, thanks!
EvoMangan
A: 

String.replaceAll(regex, replacement)

Regex can be just about everything.

Willi
I´ll try this, thanks!
EvoMangan
+3  A: 

You couldn't find any methods to find substrings or Strings that begin with or end with certain Strings? Where did you look?

danben
+3  A: 

There are various replace methods in the String class:

alt text

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

Anurag