如何在字符串数组中找到特殊的子字符串

本文关键字:字符串 数组 | 更新日期: 2023-09-27 17:57:06

我有很多字符串被拆分为许多标记(例如inArray)。我需要找到所有特殊的子字符串(例如模式)并用"NN"替换它们。每个子字符串/模式都有连接的标记,但它们可能是每个字符串数组(例如 inArray)中的单独标记,顺序很重要。例如,如果我们有:

string[] inArray0={"this", "is", "simple", "text", "for", "example", "!" };
string[] inArray1= {"Can","you","help me","please","?","thank","you","very much","." };
string[]inArray2={"How","much","is","for","example","for","testing","your","solution","."};
string[] patterns = { "the", "that", "(for width)" ,"123", ".", "text", "for example", "help me","very much"};

期望的输出是:

inArray0={ "this", "is", "simple", "NN", "NN", "NN", "!" };
inArray1= { "Can", "you", "NN", "please", "?", "thank", "you", "NN", "NN" };
inArray2={"How","much","is", "NN", "NN", "for","testing","your","solution","NN"};

我使用了Follwoing方法,但无法正常工作。

changArray(string[] inArray,string[] patterns) {

List<string> tmp = new List<string>(); foreach (string pattern in patterns) {
tmp.Add(pattern);tmp.AddRange(pattern.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));} var allPatterns = tmp.Distinct().ToList(); { if (allPatterns.Contains(inArray[i])) inArray[i] = "NN"; }

如何更改它或有其他解决方案?

如何在字符串数组中找到特殊的子字符串

这将起作用,但您需要为每个数组执行此操作。

foreach (string s in array0.Where(w => patterns.Contains(w)))
{
    S = "NN";
}

我将@JustSomeDude的代码包装成一个方法,您可以为每个输入数组调用该方法。

internal void YourDesiredMethodName (string[] input)
{
    foreach (string s in input.Where(w => patterns.Contains(w)))
    {
        s="";
        for(i=0;i<s.Split(' ').Count();i++)
        {
            if(i+1==s.Split(' ').Count())
                s += "NN";
            else 
                s += "NN ";
        }
    }
}

用法:

YourDesiredMethodName(inArray0);
YourDesiredMethodName(inArray1);
YourDesiredMethodName(inArray2);