Monick
Monick

Reputation: 11

Searching in a string a substring

I have a string (Str) with phrases separated by a character (let's define it as "%" for simple understanding). I want to search for phrases in this string (Str) that contains a word (like "dog") and put that phrase in a new string

I was wondering of a good/great way to do it.

Str is the String on which I'm going to search, "Dog" is the word I'm searching for and % is the line separator.

I already have the reader, the parser and how to save that file. I would appreciate if someone finds me an easy way to search. I can do it but I think it would be too complex meanwhile the actual solution is very easy.

I had thought about searching for the lastIndexOf("dog") and searching for the "%" in the substring of Str(0, lastIndexOf("dog") and then the second % to get the line I am searching for.

P.S: There may be two "dog" in Str and I would like to have all the lines where is showed the word "dog"

Example:

Str = " Where is my dog, john ? % your dog is on the table % really thanks john % you're welcome % Have a nice dog"

Output expected:

Where is my dog, john ? // your dog is on the table // Have a nice dog"

Upvotes: 0

Views: 152

Answers (2)

Nicholas K
Nicholas K

Reputation: 15443

You can use:

String str = "Where is my dog, john ? % your dog is on the table % really thanks john " +
             "% you're welcome % Have a nice dog";

String dogString = Arrays.stream(str.split("%"))            // String[]  
                     .filter(s -> s.contains("dog"))        // check if each string has dog
                     .collect(Collectors.joining("//"));    // collect to one string

which gives:

Where is my dog, john ? // your dog is on the table // Have a nice dog


  1. Here, the String is split into an array by using %
  2. The array is filtered to check if the split sentence contains "dog" or not.
  3. The resulting strings are concatenated into one using //.

Upvotes: 1

Manuja Jayawardana
Manuja Jayawardana

Reputation: 313

Try This Code .

Solution is Split from "%" and then check whether it contains exact word we need.

public static void main(String []args){

     String str = " Where is my dog, john ? % your dog is on the table % really thanks john % you're welcome % Have a nice dog";

     String[] words = str.split("%");
     String output = "";
     for (String word : words) {
        if (word.contains("dog")) {
            if(!output.equals("")) output += " // ";
            output += word ;
        }
     }
     System.out.print(output);
 }

Upvotes: 0

Related Questions