简体   繁体   English

c# - 如果在另一个字符串中找不到字符串,则删除它

[英]c# - erase string if its not found in another string

I cannot get this to work, its close, but not working :D My logic here seems to be a bit off, can someone help me out?我不能让它工作,它很接近,但不工作:D 我的逻辑似乎有点不对劲,有人能帮帮我吗? What i am trying to achieve is: check if string2 contains a word that does not exist in string1.我想要实现的是:检查 string2 是否包含 string1 中不存在的单词。 if this kind of word is found, print it out, and delete it如果找到这种词,打印出来,删除

string[] string1 = { "1", "2", "3" };
string[] string2 = { "1", "2", "3", "hello" };

foreach (var var2 in string2)
{
   foreach (var var1 in string1)
   {
      if (!var1.Equals(var2))
      {
         Consoleprint(var2); //print out the string that does not exist in string1[]... which is "hello"
         var2.Replace(var2, ""); //erase the unmatched string
      }
   }
}

You can switch to for loop;你可以切换到for循环; note that you should change the item of the array , string2[i] = "" , not loop variable:请注意,您应该更改数组的项目string2[i] = "" ,而不是循环变量:

for (int i = 0; i < string2.Length; ++i)
  if (!strings1.Contains(string2[i])) {
    // Let's print array item before it will be "erased"
    Consoleprint(string2[i]);

    string2[i] = "";
  }

Your main issue is trying to change the elements of an array while looping through them with a foreach .您的主要问题是尝试更改数组的元素,同时使用foreach循环它们。

Try this instead:试试这个:

string[] string1 = { "1", "2", "3" };
string[] string2 = { "1", "2", "3", "hello" };

for (int i = 0; i < string2.Length; i++)
{
   if (!string1.Contains(string2[i]))
      {
         Consoleprint(string2[i]);
         string2[i] = string2[i].Replace(string2[i], "");
      }
}

You could also .Split() the strings into List<string> like others have suggested您也可以像其他人建议的那样将字符串.Split()放入List<string>

Once you have removed the unwanted substring you can use删除不需要的子字符串后,您可以使用
string newString = String.Join("", string2)
to concat the array back together将数组连接在一起

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM