0

Here what the program is expectiong as the output: if originalString = "CATCATICATAMCATCATGREATCATCAT"; Output should be "I AM GREAT". The code must find the sequence of characters (CAT in this case), and remove them. Plus, the resulting String must have spaces in between words.

        String origString = remixString.replace("CAT", "");

I figured out I have to use String.replace, But what could be the logic for finding out if its not cat and producing the resulting string with spaces in between the words.

2
  • 1
    Please read up about replaceAll() and trim() Commented Aug 28, 2019 at 10:32
  • try this one as well - Stream.of(remixString).map(C-> C.replaceAll("(CAT)+", " ").trim()).forEach(c->System.out.println(c)); Commented Aug 28, 2019 at 11:03

3 Answers 3

2

First off, you probably want to use the replaceAll method instead, to make sure you replace all occurrences of "CAT" within the String. Then, you want to introduce spaces, so instead of an empty String, replace "CAT" with " " (space).

As pointed out by the comment below, there might be multiple spaces between words - so we use a regular expression to replace multiple instances of "CAT" with a single space. The '+' symbol means "one or more",.

Finally, trim the String to get rid of leading and trailing white space.

remixString.replaceAll("(CAT)+", " ").trim()

Sign up to request clarification or add additional context in comments.

1 Comment

I think there can be multiple CATs in between words too. so that will lead to multiple spaces in between words
0

You can use replaceAll which accepts a regular expression:

String remixString = "CATCATICATAMCATCATGREATCATCAT";
String origString = remixString.replaceAll("(CAT)+", " ").trim();

Note: the naming of replace and replaceAll is very confusing. They both replace all instances of the matching string; the difference is that replace takes a literal text as an argument, while replaceAll takes a regular expression.

2 Comments

You can use stream api also - Stream.of(remixString).map(C-> C.replaceAll("(CAT)+", " ").trim()).forEach(c->System.out.println(c));
Yes, you can use streams, but you probably shouldn't. Why create a stream for a single value and make the code that much harder to understand?
0

Maybe this will help

String result = remixString.replaceAll("(CAT){1,}", " ");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.