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!

Recommended Answers

All 3 Replies

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.

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..

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.