Friday, October 7, 2011

C# string utility functions containsAtLeastOneChar-containsOnlySpecifiedSpecChars-excludesSimilar

c-sharp-green

A utility class to perform simple operations on strings using C#. The logic is simple, one can transform the code given below to C++, PHP, or JavaScript within 2 minutes. I know each one of the programming languages I mentioned here, and all other first class modern programming languages have got sophisticated regular expression packages. But, the use of regex is not an option for everyone. Some got the skill to learn, but just don't have the time needed to read docs. Some don't want to import in a full blown namespace like System.Text.RegularExpressions
And some other are plain lazy.
Here goes the code, the names are descriptive enough, first one containsAtLeastOneChar  checks whether a string contains at least one character of a certain character set. For example, we want to check whether a password generated by a automatic password generator contains at least one capital letter, one number, and one special character.
Second one, containsOnlySpecifiedSpecChars returns true when the supplied string conains only specified characters.
Third function excludesSimilar will return true when a string does not contain repeating characters.
The class Commons contains static member variables, you could try passing these values to the static member functions of this class and experiment  around to check the results. It will also save you some typing :)
You could just copy paste the code given below as it is, it's supposed to work.
Happy coding!
public class Commons
{
public static bool containsAtLeastOneChar(string strWord, string strCompairTo)
{
 int nIdx = -1;
 foreach (char c in strWord)
 {
  nIdx = strCompairTo.IndexOf(c);
   if (nIdx >= 0) return true;
 }
 return false;
}
public static bool containsOnlySpecifiedSpecChars(string strWord, string strSpecialChars)
{
foreach (char c in strWord)
 {
  if ((strCaps.IndexOf(c) < 0) & (strSmalls.IndexOf(c) < 0) & (strNums.IndexOf(c) < 0))
 {
  if (strSpecialChars.IndexOf(c) < 0)
   return false;
  }
}
return true;
}
public static bool excludesSimilar(string strWord)
{
foreach (char c in strWord)
{
 if (strWord.IndexOf(c) != strWord.LastIndexOf(c))
  return false;
 }
 return true;
}

public static string strCaps = "ABCDEFGHIKLMNOPQRSTUVWXYZ";
public static string strSmalls = "abcdefghijklmnopqrstuvwxyz";
public static string strNums = "0123456789";
}//class

2 comments:

  1. Android users can use a variety of tools to edit apk files, including Android Studio, a built-in editor for the Android platform. However, some users may prefer to use an external editor. There are many Editors available on the Play Store and they come with different features and price tags. It is important to choose an Editor that will meet your needs and fit your budget.

    ReplyDelete

Feel free to talk back...