字符串的IndexOf和替换 [英] string IndexOf and Replace

查看:346
本文介绍了字符串的IndexOf和替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天刚遇到这个问题,不知道是否有人有关于为什么会发生这种测试可能会失败(取决于文化)的想法。这样做的目的是为了检查测试文本包含两个空格彼此相邻,这并根据 string.IndexOf (即使我告诉字符串替换两个所有出现空间彼此相邻)。经过一些测试,似乎 \ XAD 由于某种原因导致此问题。

 公共类ReplaceIndexOfSymmetryTest
{
    [测试]
    公共无效IndexOfShouldNotFindReplacedString()
    {
        字符串testText =\ X61 \ X20 \ XAD \ X20 \ X62;
        常量字符串TWO_SPACES =;
        常量字符串ONE_SPACE =;
        字符串结果= testText.Replace(TWO_SPACES,ONE_SPACE);
        Assert.IsTrue(result.IndexOf(TWO_SPACES)℃,);
    }
}
 

解决方案

是的,我遇到了同样的事情之前(虽然不同的字符)。基本上的IndexOf 将采取特别统一code字各方面的考虑寻找匹配时,而替换只是把字符串为code点的序列。

的IndexOf 文档

  

此方法执行单词(区分大小写和文化敏感)使用当前区域性的搜索。搜索开始于该实例的第一个字符位置,并继续,直到最后一个字符的位置。

...从 替换

  

此方法执行序号(区分​​大小写和不区分区域性)搜索找到的属性oldValue。

您可以使用的IndexOf 的重载这需要一个<一个href="http://msdn.microsoft.com/en-us/library/system.stringcomparison.aspx"><$c$c>StringComparison,并迫使它虽然执行序号比较。

I have just faced this problem today and wonder if someone has any idea about why does this test may fail (depending on culture). The aim is to check if the test text contain two spaces next to each other, which does according to string.IndexOf (even if i tell the string to replace all occurrences of two spaces next to each other). After some testing it seems \xAD is somehow causing this issue.

public class ReplaceIndexOfSymmetryTest
{
    [Test]
    public void IndexOfShouldNotFindReplacedString()
    {
        string testText = "\x61\x20\xAD\x20\x62";
        const string TWO_SPACES = "  ";
        const string ONE_SPACE = " ";
        string result = testText.Replace(TWO_SPACES, ONE_SPACE);
        Assert.IsTrue(result.IndexOf(TWO_SPACES) < 0);
    }
}

解决方案

Yes, I've come across the same thing before (although with different characters). Basically IndexOf will take various aspects of "special" Unicode characters into account when finding matches, whereas Replace just treats the strings as a sequence of code points.

From the IndexOf docs:

This method performs a word (case-sensitive and culture-sensitive) search using the current culture. The search begins at the first character position of this instance and continues until the last character position.

... and from Replace:

This method performs an ordinal (case-sensitive and culture-insensitive) search to find oldValue.

You could use the overload of IndexOf which takes a StringComparison, and force it to perform an ordinal comparison though.

这篇关于字符串的IndexOf和替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆