1.11M Members

Help for replacing word in string

 
0
 

Hi all,

I want to ask a question about replacing specific word in a string

for example I have a string of:
input = a fast nope e

i want to replace word "a", if I use method replace which is:
input.replace("a", "hello");

the character a in fast will also be replaced becoming:
hello fhellost nope e

So how I can solve it?
Thanks guys!

 
0
 

Use split("//s") on your String object to form an array of words from the input. Then, reassemble the string, using your replacement word for the first element of the returned array, and the rest of the words in order from the array.

A best practice is to use a StringBuffer to construct your new string using the append method for each word, and when constructed, use toString() to get the final string value, but this is not absolutely necessary.

 
0
 

Use split("//s") on your String object to form an array of words from the input. Then, reassemble the string, using your replacement word for the first element of the returned array, and the rest of the words in order from the array.

A best practice is to use a StringBuffer to construct your new string using the append method for each word, and when constructed, use toString() to get the final string value, but this is not absolutely necessary.

Hi thanks for your response..by the way it is not the full case what I face right now..:)

The real case is:
- I have an input from user in a text area
- I retrieve the input, and try to correct the error input that is not in my dictionary
For example:
input: H my a is Andy
So, H and a are error words
- There is a list of my words in dictionary to correct them
But I have tried to manipulate input by splitting input with " " and replace the array and replace error word with correct word and now I face how to reassemble the words again into one string, because I must deal with the space.

Is there any other solution to help solving this problem? I have dealt with this thing for 3 hours and got no result..
also is there any solution how to face input that has newline? :) I think this one can't be solved by using split..

 
0
 

Well, I think you can first separate your input into paragraphs with split(""\\r?\\n") (I believe that's the right regex). A newline in the text would effectively mean it's a new paragraph, right? Each paragraph would go into its own ArrayList. You can keep those array lists in another array list so you don't have to worry about keeping track of individual array lists.

As far as the spaces go, just concatenate all the words with a space after each one, then use trim() to remove the final space. Or, use some logic to know that you don't add a space after the last word in the paragraph.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: