How can i check of a string contains a letter space letter space and anotherl letter C#

StackOverflow https://stackoverflow.com/questions/22661892

  •  21-06-2023
  •  | 
  •  

Question

I need help to check if a string contains a word like: P I E T S N O T . C O M

I don't want it to say true when I have it like this: "Hi my name is" etc., only if it is 1 letter space 1 letter and that 3 times or more in a string. This is for my game's banfilter. I dont want that peaple can say Hi come to my game H I H I H I . C O M

I can't figure it out because I don't want to add all the combinations for 1 word.

Was it helpful?

Solution

Strictly following your requirement, everything that is not a letter followed by a space and repeat the sequence until the end of the string

void Main()
{
    string test = "P I E T S N O T . C O M";
    Console.WriteLine(CheckSpaceLetterSequence(test));
    test = "Hi my name is";
    Console.WriteLine(CheckSpaceLetterSequence(test));
}


bool CheckSpaceLetterSequence(string test)
{
    int count = 0;
    bool isSpace = (test[0] == ' ');
    for(int x = 1; x < test.ToCharArray().Length; x++)
    {
        bool curSpace = (test[x] == ' ');
        if(curSpace == isSpace)
            return false;

        isSpace = !isSpace;
        count++;
        if(count == 3)
           break;
    }
    return true;
}

OTHER TIPS

This should do the trick:

bool allLetterSpace = text.Trim().Length >= 6 && text.Trim()
   .Select((c, i) => new { IsWhiteSpace= Char.IsWhiteSpace(c), Index = i })
   .All(x => x.Index % 2 == 1 ? x.IsWhiteSpace : !x.IsWhiteSpace);
string word = "Hello, my name is f i s h b i s c u i t s";

if (word.Replace(" ", "").Contains("fishbiscuits"))
{
 // code here
}

This will tell you if every other character in text is a space:

bool spaced = text.Select((c,i) => (c == ' ') == (i % 2 == 1)).All(b => b);

A Regular expression solution could look like this:

Regex regex = new Regex(@"(?<name>(?:[A-Z.] ){2,}[A-Z.])");
Match m = regex.Match("P I E T S N O T . C O M");
if (m.Success)
    MessageDlg.Show("Name is " + m.Groups["name"].Value);
else
    MessageDlg.Show("No name found");

If you need it to match more letters than capital letters and dot, you should extend the two [A-Z.] to e.g. [A-Za-z0-9.,-_].

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top