Beginners question

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
 
J

Jhon

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
 
J

Jon Skeet [C# MVP]

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"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

learning to code - dictionary question 8
Nullable class 2
Odd Shadowing behaviour 1
Q: Inherit string type, possible? 11
How to replace escaped strings? 6
reference type 4
IFormattable interface 3
Thread 1

Top