简体   繁体   中英

Replace a substring of arbitrary length

I need to replace a substring of arbitrary length. For example between two spaces.

Example

String str = "Insert random message here";
// Manipulation
System.out.println(str);

// Outputs: Insert a message here

I have searched for a method in the String-class but I haven't found a useful one. (It might be because my bad English...)

System.out.println gives me a feeling that this is Java. You can use the object's replaceAll function to replace a string block/matching regex with another given string.

String str = "I am foo";
str.replaceAll("foo", "blah");
System.out.println(str);

Above code should print "I am blah".

The most immediate solution is to use a pair of substring calls and concatenate the results:

String random = "random"
String str = "Insert random message here";

int nStart = str.indexOf(random);
int nEnd = nStart + random.length;

str = str.substr(0,nStart) + str.substr(nEnd);
System.out.println(str);

// Outputs: Insert a message here
  • note that my math is terrible, so the numbers are probably off by one or two!

  • Edited to use variables instead of "magic numbers"

Edited to add: I may not be using the same language as the OP, but hopefully it's close enough to be understood.

You can use replaceFirst with this regex \\s(.*?)\\s which mean match the first word between two spaces like this :

String str = "Insert random message here";
str = str.replaceFirst("\\s(.*?)\\s", " a ");
System.out.println(str);

Output

Insert a message here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM