C#通过忽略转义序列来比较subString&特殊字符

时间:2015-06-06 16:05:41

标签: c#

String str = "Hello!I'm new here and this is my first question."

String str2 = "Hello Im new here."

// here i want to get index by ignoring special characters 
int startIndex = str1.IndexOf(str2);

如果你能帮助我,我们将非常感激。我一直在搞乱代码和google几天,但都是徒劳。

1 个答案:

答案 0 :(得分:4)

我认为你想要的东西可以通过Regex使用模式

来实现

IndexOf()

匹配任何非单词字符(任何不是[a-zA-Z0-9])。

使用此模式,您可以对两个字符串进行临时替换,然后执行using System; using System.Text.RegularExpressions; public class Program { public static void Main() { string str = "Hello!I'm new here and this is my first question."; string str2 = "Hello Im new here."; string tempStr = Regex.Replace(str, "\\W+", ""); string tempStr2 = Regex.Replace(str2, "\\W+", ""); int startIndex = tempStr.IndexOf(tempStr2); Console.WriteLine(tempStr); Console.WriteLine(tempStr2); Console.WriteLine("Index of str2 starts a {0} ", startIndex); } } 。类似的东西:

HelloImnewhereandthisismyfirstquestion
HelloImnewhere
Index of str2 starts a 0

结果:

int * p = new int[2];
p[0] = 0;
p[1] = 1;
p++;
cout<<*p<<"\n";

请在此处查看工作示例... https://dotnetfiddle.net/XIpcj0