-2

I have one string : String a = "Today is my 'birthday' and i am celebrating with my 'friends'. friends is 'the' best part of life"

now I want to replace string inside quote '' with test word like 'birthday' replace with test. but replace only character which is coming after my word. like 'the' will not replace. string can change runtime this is sample string how can i achieve this.

aj0822ArpitJoshi
  • 1,142
  • 1
  • 9
  • 25
  • A lot of complications in your description. A better way would be if you write what exactly your string should look like after replacing it. – Kunu Mar 30 '21 at 12:40
  • some string coming after word my : like birthday coming after my word so this will replace with test word. – aj0822ArpitJoshi Mar 30 '21 at 12:49
  • [https://stackoverflow.com/questions/55863995/find-next-word-of-a-word-from-a-string](https://stackoverflow.com/questions/55863995/find-next-word-of-a-word-from-a-string) This can help you find the next word to "my" (in your case0 – Kunu Mar 30 '21 at 12:55
  • Then replace that as per your requirement. – Kunu Mar 30 '21 at 12:56
  • Give us a better example: base text, word to replace, replace word, end result which you will expect. With such description it's really hard to understand what you are trying to achieve – hardartcore Mar 30 '21 at 12:56
  • Check the different methods of `String`, like `subString()`, `indexOf()`, `replace()`, etc. – Bruno Mar 30 '21 at 13:06

1 Answers1

0

I didn't get your question well. But these approaches may help. You can try string replace like this:

String a = "Today is my 'birthday' and i am celebrating with my 'friends'. friends is 'the' best part of life";
a = a.replace("'birthday'", "'first day'");
a = a.replace("'friends'", "'family'");
a = a.replace("'the'", "'one of the'");
System.out.println(a);

Output:

Today is my 'first day' and i am celebrating with my 'family'. friends is 'one of the' best part of life

Or if you can parameterize the message strings then do it like this.

String b = "Today is my {0} and i am celebrating with my {1}. friends is {2} best part of life";
String[] arguments = {"first day", "family", "one fo the"};
b = MessageFormat.format(b, arguments);
System.out.println(b);

For more information refer MessageFormat class.
There is already a huge discussion here How to format strings in Java

the Hutt
  • 16,980
  • 2
  • 14
  • 44