Search code examples
c#replacecontains

How do I check if a string contains a certain word and then delete that said word?


I wanted it to work like this

sentence: "random sentence correct"

result: "random sentence"

Here is my current code:

for(int x = 0; x < answers.Count; x++)
{
    if(answers[x].Contains(" correct"))
    {
        answers[x].Replace(" correct", "");
        keys.Add(answers[x]);
    }
}

This code doesn't replace the said word for some reason

Or if it's impossible. Can I just delete the last word of the string?

So if the string is "this is a sentence correct"

the result will be "this is a sentence"


Solution

  • answers[x] = answers[x].Replace(" correct", "");
    

    every string manipulation function(like Replace in this example) returns a new string since strings are immutable in c#

    you can read more about it here