0

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...)

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84

3 Answers3

1

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".

Parijat Purohit
  • 921
  • 6
  • 16
0

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.

theGleep
  • 1,179
  • 8
  • 14
  • How would the OP get the numbers 6 and 13 in code, as *arbitrary length* implies? – Andrew Morton Sep 19 '17 at 17:14
  • But what if "random" doesn't exist in the scentence input? What if i have a random scentence and i just want to pick out ONE between two spaces? Doesn't this sollution imply that the Word "random " must be included? – randy costanza Sep 19 '17 at 17:34
  • Ah ... that's a bit of a different question. But I'll try to answer as clearly as possible. The variables are placeholders to be filled in. If you need to remove the second word, you can use an "indexOf" type function to find the first and second spaces. Or you could have a User Interface where the user would specify. The *cause* of abitrariness is directly related to how you will define start and end – theGleep Sep 19 '17 at 17:39
  • Hmmmm... Don't really get it. Do you have a simple example? – randy costanza Sep 19 '17 at 17:56
0

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140