A quick way to check if a string is "mainly" capital

I am writing a bot in C # for chat, and I want to determine if the message contains too many capital letters. A message contains too many capital letters if its total number of capital letters exceeds one-thirdits total message length and if its total length is greater than 13. This is to prevent tagging from smaller posts.

Right now, I look through each character and see that it is uppercase. This is normal for a reasonable message. However, if you receive a spammer or troll, they will not always send messages of reasonable duration. The maximum character limit 2000, and I can’t change it. With my method, it starts to stop around characters 500+. This gives the spammer enough time to insert a message and send it again, effectively chatting while the bot is struggling to keep up.

The code I have is:

bool isMostlyUpper = (message.Count(c => char.IsUpper(c)) >= message.Length * 0.3f) && message.Length > 13;

I cannot compare the message with string.ToUpper(), because I still want to determine if the message is mostly uppercase, not uppercase.

Is there a way to do this without skewing over each char? Or a way to get to the result faster? I can add checks to see if there is a message > 500, but sometimes there are long messages 500+that you can go through.

Does anyone have smart solutions? Thank.

+4
source share
2 answers

If you get out of your loop when you reach your state, in some cases you will save time

int count = 0;
float maxLenght = message.Length * 0.3f;
bool isMostlyUpper = false;

foreach (char c in message)
{
    if (char.IsUpper(c))
    {
        count++;
    }

    if(count >= maxLenght)
    {
        isMostlyUpper = true;
        break;
    }

}

You can also track the last message that was flagged and compare it with the new message received so that it would not allow people to spam the same message, and you would not have to recount the same message several times.

+2

,

private static bool IsMostlyUpper (string message)
{
    if (message.Length > 13) {
        int step = 1 + message.Length / 100; // integer division.
        // 1 for message length < 100
        // 2 for message length < 200
        // 3 for message length < 300

        int limit = message.Length / step / 3;
        int upperCase = 0;
        for (int i = 0; i < message.Length; i += step) {
            if (Char.IsUpper(message[i])) {
                upperCase++;
                if (upperCase >= limit) {
                    return true;
                }
            }
        }
    }
    return false;
}

.


, ,

private static Random _random = new Random(); // static field

int divisor = _random.Next(150, 200);
int step = 1 + message.Length / divisor;

!

0

Source: https://habr.com/ru/post/1682428/


All Articles