Joseph Lafuente
Joseph Lafuente

Reputation: 2165

How to Replace a word in a String with a blank in C#?

Any algorithm which changes a word from a string to a blank? I'm having problems with this.

my scenario is replacing a word to a blank but some words are also found inside another word so what happens is it also replaces the certain string in that word.

Ex. Hello Ello llo lo o

if I replace llo with _

output: He___ E__ ____ lo o

Upvotes: 0

Views: 567

Answers (3)

Dan Tao
Dan Tao

Reputation: 128317

I think you should have some luck with Regex.Replace and using the word boundary special character (\b) to indicate word boundaries. I'm no expert, though. But do try that.

Example:

string input = "llo Hello Ello llo lo o llo, and oh hello llo! Look, a yellow llo.";
string output = Regex.Replace(input, @"\bllo\b", "___");
Console.WriteLine(output);

Output:

___ Hello Ello ___ lo o ___, and oh hello ___! Look, a yellow ___.

Note this caught the "llo" at the beginning, as well as those followed by punctuation ("llo,", "llo!", and "llo.") without erroneously stripping out those that were part of other words ("Hello", "Ello", "yellow").


Edit: The following is in response to your comment. My understanding is that you have two TextBoxes, preview and question, and a ListBox, chosenwordlist. I believe this is what you want to do:

// Start by setting preview to the same text as question.
preview.Text = question.Text;

for (int i = 0; i < chosenwordlist.Items.Count; ++i)
{
    string word = chosenwordlist.Items[i].ToString();

    // Notice the verbatim literal (@) for the SECOND "\b" as well.
    string pattern = @"\b"+ word + @"\b";

    // Since the text in your question TextBox isn't changing, you need to base each
    // replacement off of what's in the preview TextBox, which IS (changing).
    preview.Text = Regex.Replace(preview.Text, pattern, "__________");
}

Upvotes: 3

Tedd Hansen
Tedd Hansen

Reputation: 12360

I hope I have understood you correctly. Using Regex you can achieve this:

Regex myRegex = new Regex(@"(?<![a-z])[a-z](?![a-z])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Debug.WriteLine(myRegex.Replace("test-a-b-c-test", "!"));

Will print: test-!-!-!-test
From the original string: test-a-b-c-test

Upvotes: 0

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29975

You can use regular expressions http://www.regular-expressions.info/dotnet.html

Upvotes: 1

Related Questions