-3

I have a Sentence

String query = "This is a sample Sentence"

I extracted all the words from it.

 String[] queryWords = query.split(" ");

... and this gives;

[ "This", "is", "a", "simple", "sentence"]

Now I want to add wildcards to each word.

[ "%This%" , "%is%" , "%a%" , "%simple%" , "%sentence%" ]

To add % symbol at the beginning and end of each word.

How can i do this?

3
  • Do you know how to concatenate strings? Commented Nov 3, 2015 at 17:33
  • queryWords[i] = "%" + queryWords[i] + "%"; in a loop Commented Nov 3, 2015 at 17:34
  • 3
    Possible duplicate of java replace certain string in array of strings Commented Nov 3, 2015 at 17:41

3 Answers 3

3

Iterate over all strings in queryWords and replace with a new String that is the old String with the '%' added at the beginning and the end

for (int i = 0; i < queryWords.length; ++i) {
    queryWords[i] = '%' + queryWords[i] + '%';
}
Sign up to request clarification or add additional context in comments.

Comments

3

If you want to use Stream,

queryWords = Arrays.stream(queryWords).map(s -> "%"+s+"%").toArray(String[]::new);

1 Comment

Thanks. will update to this code when i upgrade to java8
0

You can do a for loop over the array like

    for(int i = 0; i< test.length; i++){
        s[i] = "%" + s[i] + "%";
    }

http://schabby.de/java-for/

4 Comments

it is look in the tags =)
"for each" is not Java.
This will only change the local s variable, not what is in queryWords.
for each can be used in java.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.