prameela rani prameela rani - 1 year ago 166 Question

how to check if string has consecutive characters in

I'm trying to check if a string contains consecutive characters in


'test@01' - not ok
'test@02 - ok
'testab' - not ok
'testac' - ok
'testabc' not ok

string should not have any consecutive characters. (both numbers & alphabets) alphanumeric

Any help is appreciated.

Answer Source

You problem is very vague one. Let alone the language (C# or VB) there're many ambiguities:

  • Is "cba" OK (conseq. but in descending order)?
  • Is "aBc" OK (conseq. when case is ignored)?
  • Is "x@A" OK (according ascii charater table '@' preceeds 'A')?

in case when the answers are all No's (ascending order only, case sensitive, both characters must be letters and digits only), a simple loop solves the task (C#):

  string source = "test@01";
  bool result = false;

  for (int i = 1; i < source.Length; ++i)
    if (char.IsLetterOrDigit(source[i]) && char.IsLetterOrDigit(source[i - 1]))
      if (source[i] - source[i - 1] == 1) { 
        result = true;



Console.Write(result ? "OK" : "Not OK");

Edit: if you want case insensitive test you have to compare

 if (char.ToUpperInvariant(source[i]) - char.ToUpperInvariant(source[i - 1]) == 1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download