Beginners question

  • Thread starter Thread starter Andy Hoe
  • Start date Start date
A

Andy Hoe

Hello, I'm new to C# and I am having a small problem. All I want to do is
take a sentence from the user then replace certain words with other ones.
So I started off with this:

string myString = Console.ReadLine();
string editString;
editString = myString.Replace("is", "isn't");
Console.WriteLine(editString);

Which if I entered "This is a test" I got back "Thisn't isn't a test"
I got round this by looking for the word to replace by putting spaces round
the string:

string myString = Console.ReadLine();
string editString;
editString = myString.Replace(" is ", " isn't ");
Console.WriteLine(editString);

Which was fine for this example, but what if there is punctuation involved?
what if I wanted to convert "This is." it wouldn't pick it up because of the
full stop. Would it be best to do it a different way by stripping all the
punctuation out somehow? but then how would you put it back in? is there a
simple way of doing this?
Thanks for any help,
Andy
 
Hi,

Regular expressions have a zero-width assertation \b. This specifies that
the match must occur on a word boundary.

using System.Text.RegularExpressions;
string myString = Console.ReadLine();
string editString;
editString = Regex.Replace (myString,"\\bis","isn't");
Console.WriteLine(editString);


HTH
greetings
 
Carol Sun said:
Why don't you say
editString = myString.Replace (" is", " isn't");

That has the same problem with other words:

"This is an issue that needs resolving" would become
"This isn't an isn'tsue that needs resolving"
 
Back
Top