簡體   English   中英

C#通過忽略轉義序列和特殊字符來比較subString

[英]C# Compare subString by ignoring escape sequences & Special Characters

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);

如果您能幫助我,將不勝感激。 我一直在混亂的代碼和谷歌好幾天了,但都是徒勞的。

我認為您想要的可以通過Regex使用該模式來實現

"\\\\W+"

匹配任何非單詞字符(不是[a-zA-Z0-9]的任何字符)。

使用此模式,您可以對兩個字符串進行臨時替換,然后執行IndexOf() 就像是:

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

在這里查看工作示例... https://dotnetfiddle.net/XIpcj0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM