这是一个非常基本的问题,但我不确定为什么它不起作用。我有代码,其中“和”可以用“和”、“和”等任何方式编写,我想用“,”替换它
我试过这个:
and.Replace("and".ToUpper(),",");
但这不起作用,还有其他方法可以做到这一点或使它起作用吗?
你应该看看 Regex 类
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, ",");
我想你应该小心一些词是否包含and
,说"this is sand and sea"
。“沙子”这个词一定不能受到替换的影响。
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));
我也会像这样添加:
and = and.Replace(" , ", ", ");
所以,输出:
this is sand, sea
words = words.Replace("AND", ",")
.Replace("and", ",");
或者使用正则表达式。
该Replace
方法返回一个替换可见的字符串。它不会修改原始字符串。你应该尝试一些类似的东西
and = and.Replace("and",",");
您可以为您可能遇到的所有“和”变体执行此操作,或者正如其他答案所建议的那样,您可以使用正则表达式。
尝试这种方式使用静态Regex.Replace()
方法:
and = System.Text.RegularExpressions.Regex.Replace(and,"(?i)and",",");
"(?i)" 导致以下文本搜索不区分大小写。
http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx
http://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.100).aspx