0

I am trying to compare a string to see if it contains a curse word. I assumed that I could do this using str.Contains("" || "") although I quickly realized I cannot use || with two strings. What would I use in place of this?

str.Contains("123" || "abc");

I expected it to see if it contains 123 or abc but the code segment does not work as it cannot compare two strings.

Jonathan Willcock
  • 5,012
  • 3
  • 20
  • 31
Nate
  • 1
  • 2

4 Answers4

2
var str = "testabc123";
var str2 = "helloworld";
var bannedWords = new List<string>
{
    "test",
    "ok",
    "123"
};
var res = bannedWords.Any(x => str.Contains(x));       //true
var res2 = bannedWords.Any(x => str2.Contains(x));     //false

You can do something like this. Create a list with the swear words, then you can check if the string contains any word in the list.

gxexx
  • 99
  • 1
  • 9
0

Try -

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var input = "some random string with abc and 123";
        var words = new List<String>() {"123", "abc"};

        var foundAll = words.Any(word => input.Contains(word));

        Console.WriteLine("Contains: {0}", foundAll);
    }
}
Parag Meshram
  • 8,281
  • 10
  • 52
  • 88
0

Try the following approach

using System;
using System.Collections.Generic;

public class Program
{
    private static final List<String> curseWords = new List<String>() {"123", "abc"};

    public static void Main()
    {
        String input = "text to be checked with word abc";    

        if(isContainCurseWord(input)){
            Console.WriteLine("Input Contains atlease one curse word");
        }else{
            Console.WriteLine("input does not contain any curse words")
        }

    }

    public static bool isContainCurseWord(String text){

        for(String curse in curseWords){
            if(text.Contains(curse)){
                return true;
            }
        }
        return false;
    }   
}
-1

Try -

var array = new List<String>() {"123", "abc"};

var found = array.Contains("abc");

Console.WriteLine("Contains: {0}", found);
Parag Meshram
  • 8,281
  • 10
  • 52
  • 88
  • 1
    Thank you, this solution allows me to cleanly add a lot more words to filter. It is very helpful, thank you so much. – Nate Jun 26 '19 at 04:25