简体   繁体   中英

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? What i am trying to achieve is: check if string2 contains a word that does not exist in 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; note that you should change the item of the array , string2[i] = "" , not loop variable:

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 .

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

Once you have removed the unwanted substring you can use
string newString = String.Join("", string2)
to concat the array back together

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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