c#中的字符串和数组操作

本文关键字:数组 操作 字符串 | 更新日期: 2023-09-27 18:08:55

下面是代码,对于单个输入字符串

,它工作得很好
string[] stop_word = new string[] 
{ 
    "please", 
    "try", 
    "something", 
    "asking", 
    "-", 
    "(", ")", 
    "/", 
    ".", 
    "was", 
    "the" 
};
string str = "Please try something (by) yourself. -befor/e asking";
foreach (string word in stop_word)
{
    str = str.ToLower().Replace(word, "").Trim();
}

,输出为by yourself before现在我想用

string str[] = new string[] 
{ 
    "Please try something-by yourself. before (CAD) asking/", 
    "cover, was adopted. The accuracy (of) the- change map was" 
};

,也可能是字符串的数量大于2,那么如何修改上面的代码来显示str数组或存储在文本文件或数据库中。

请帮忙致谢。由于

c#中的字符串和数组操作

单个字符串的代码需要放在字符串数组

的循环中
List<string> result = new List<string>();
for(int i =0; i<str.Length; i++)
{
    foreach (string word in stop_word)
    {
        str[i] = str[i].ToLower().Replace(word, "").Trim();
        str[i] = Regex.Replace(str[i], @"'s+", " ");
    }
    result.Add(str[i]);
}
foreach(string r in result)
{
    //this is to printout the result
    Console.WriteLine(r); 
}

您可以在这里尝试:https://dotnetfiddle.net/wg83gM

编辑:

使用正则表达式将多个空格替换为一个空格

这里有一个简单易懂的方法:

List<string> list = new List<string>();
foreach (string text in str)//loops through your str array
{
   string newText =text;
   foreach (string word in stop_word) //loops through your word array
    {
       newText =  newText.ToLower().Replace(word, "").Trim();
   }
   list.Add(newText);  //store the results in a list
}

这是一个工作演示

是否如您所愿?

var results =
    str
        .Select(x => stop_word.Aggregate(x, (a, y) => a.ToLower().Replace(y, "").Trim()))
        .ToArray();

我使用了这个输入:

string[] str = new string[]
{
    "Please try something-by yourself. before (CAD) asking/",
    "cover, was adopted. The accuracy (of) the- change map was"
};
string[] stop_word = new string[]
{
    "please", "try", "something", "asking", "-", "(", ")", "/", ".", "was", "the"
};

我得到了这样的输出:

by yourself before cad 
cover,  adopted  accuracy of  change map 

您可以使用Select()

var results = str.Select(x => {
    foreach (string word in stop_word)
    {
        x = x.ToLower().Replace(word, "").Trim();
    }
    return x;
}).ToList(); // You can use ToArray() if you wish too.
...
foreach(string result in results)
{
    Console.WriteLine(result);
}
结果:

by yourself before cad

封面,采用的变化图精度