【问题标题】:How to replace a word in a string如何替换字符串中的单词
【发布时间】:2012-09-13 10:12:57
【问题描述】:

这是一个非常基本的问题,但我不确定为什么它不起作用。我有代码可以用“And”、“and”等任何方式编写“And”,我想用“,”替换它

我试过了:

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

但这不起作用,还有其他方法可以做到这一点或使它起作用吗?

【问题讨论】:

  • 相当于and.Replace("AND", ",")。无论如何,请查看 Regex.Replace 和不区分大小写模式。
  • 正如@pst 提到的,您也可以使用正则表达式:var regex = new Regex( "camel", RegexOptions.IgnoreCase ); var newSentence = regex.Replace( sentence, "horse" ); 代码取自:stackoverflow.com/questions/6025560/…
  • 您还可以在搜索模式中使用“(?i)and”选项。这样您就可以使用静态Replace() 方法,因为您不需要使用RegexOption.IgnoreCase 枚举。我在下面给出了一些代码。
  • 你应该考虑到这个句子可以包含像“sand”这样的词。正则表达式也将替换它们。这是不正确的。
  • 我创建了一个 StringExtensions 项目,它提供了一个重载 Replace 并采用了 ComparisonType,请参阅:stringextensions.codeplex.com/SourceControl/changeset/view/… 现在,您可以简单地说:mystring.Replace("and", ",", StringComparison.InvariantIgnoreCase); 这比任何正则表达式解决方案都更高效

标签: c# string replace


【解决方案1】:

你应该看看 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, ",");

【讨论】:

  • 善用\b (+1)。我更喜欢使用 Regex 静态方法,但这主要是偏好..
【解决方案2】:
words = words.Replace("AND", ",")
             .Replace("and", ",");

或者使用正则表达式。

【讨论】:

  • 他其实没有提到,但我认为你必须考虑AndaNdANd输入等。所以,将输入字符串和搜索字符串转换为偶数和进行替换,或仅使用正则表达式。
  • @Jack 是的,这只是一个例子。我的意思是他可以继续链接 .Replace 方法或您的 RegEx,正如我提到的。由于它只是有限数量的组合。替换并不是那么糟糕。
【解决方案3】:

Replace 方法返回一个替换可见的字符串。它修改原始字符串。你应该尝试一下

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

您可以为您可能遇到的所有“和”变体执行此操作,或者正如其他答案所建议的那样,您可以使用正则表达式。

【讨论】:

  • 虽然是真的,但这对“杰克和吉尔”没有帮助。
【解决方案4】:

我想你应该小心一些单词是否包含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

【讨论】:

    【解决方案5】:

    尝试这种方式使用静态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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-03
      • 2021-10-02
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      相关资源
      最近更新 更多