NoviceMe
NoviceMe

Reputation: 3256

How to replace a word in a string

It is very basic question but i am not sure why it is not working. I have code where 'And' can be written in any of the ways 'And', 'and', etc. and i want to replace it with ','

I tried this:

and.Replace("and".ToUpper(),",");

but this is not working, any other way to do this or make it work?

Upvotes: 2

Views: 1978

Answers (5)

Rick Su
Rick Su

Reputation: 16440

You should check out the Regex class

http://msdn.microsoft.com/en-us/library/xwewhkd1.aspx

using System.Text.RegularExpressions;

Regex re = new Regex("\band\b", RegexOptions.IgnoreCase);

string and = "This is my input string with and string in between.";

re.Replace(and, ",");

Upvotes: 6

horgh
horgh

Reputation: 18534

I guess you should take care if some words contain and, say "this is sand and sea". The word "sand" must not be influenced by the replacement.

string and = "this is sand and sea";

//here you should probably add those delimiters that may occur near your "and"
//this substitution is not universal and will omit smth like this " and, " 
string[] delimiters = new string[] { " " }; 

//it result in: "this is sand , sea"
and = string.Join(" ", 
                  and.Split(delimiters,  
                            StringSplitOptions.RemoveEmptyEntries)
                     .Select(s => s.Length == 3 && s.ToUpper().Equals("AND") 
                                     ? "," 
                                     : s));

I would also add smth like this:

and = and.Replace(" , ", ", ");

So, the output:

this is sand, sea

Upvotes: 2

Matt Klein
Matt Klein

Reputation: 8424

try this way to use the static Regex.Replace() method:

and = System.Text.RegularExpressions.Regex.Replace(and,"(?i)and",",");

The "(?i)" causes the following text search to be case-insensitive.

http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx

http://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.100).aspx

Upvotes: 0

K Mehta
K Mehta

Reputation: 10533

The Replace method returns a string where the replacement is visible. It does not modify the original string. You should try something along the lines of

and = and.Replace("and",",");

You can do this for all variations of "and" you may encounter, or as other answers have suggested, you could use a regex.

Upvotes: 2

lahsrah
lahsrah

Reputation: 9173

words = words.Replace("AND", ",")
             .Replace("and", ",");

Or use RegEx.

Upvotes: 2

Related Questions