Home > Software design >  c# - erase string if its not found in another string
c# - erase string if its not found in another string

Time:06-30

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
      }
   }
}

CodePudding user response:

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] = "";
  }

CodePudding user response:

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

  • Related