Skip to content

Instantly share code, notes, and snippets.

@justinormont
Created July 9, 2019 17:14
Show Gist options
  • Save justinormont/ead021d89be98892890c118328068fbf to your computer and use it in GitHub Desktop.
Save justinormont/ead021d89be98892890c118328068fbf to your computer and use it in GitHub Desktop.
String Statistics
// Note: Some of these functions are likely better left to the .NET language's implementation for better internalization support.
// Using a regex for these was found to be slower.
Func<char, bool> isVowel = ((x) => x == 'e' || x == 'a' || x == 'o' || x == 'i' || x == 'u' || x == 'E' || x == 'A' || x == 'O' || x == 'I' || x == 'U' );
Func<char, bool> isConsonant = ((x) => (x >= 'A' && x <= 'Z')||(x >= 'a' && x <= 'z') && !(x == 'e' || x == 'a' || x == 'o' || x == 'i' || x == 'u' || x == 'E' || x == 'A' || x == 'O' || x == 'I' || x == 'U'));
Func<char, bool> isVowelOrDigit = ((x) => x == 'e' || x == 'a' || x == 'o' || x == 'i' || x == 'u' || x == 'E' || x == 'A' || x == 'O' || x == 'I' || x == 'U' || (x >= '0' && x <= '9'));
Func<string, int> maxRepeatingCharCount = ((s) => { int max = 0, j = 0; for (var i = 0; i < s.Length; ++i) { if (s[i] == s[j]) { if (max < i - j) max = i - j; } else j = i; } return max; });
Func<string, int> maxRepeatingVowelCount = ((s) => { int max = 0, j = 0; for (var i = 0; i < s.Length; ++i) { if (s[i] == s[j] && isVowel(s[j])) { if (max < i - j) max = i - j; } else j = i; } return max; });
// --------- //
string text = (I.text is string ? (string)(object)I.text : string.Join(" ", I.text) );
O.length = text.Length;
O.vowelCount = text.Count(isVowel);
O.consonantCount = text.Count(isConsonant);
O.numberCount = text.Count(Char.IsDigit);
O.underscoreCount = text.Count(x => x == '_');
O.letterCount = text.Count(Char.IsLetter);
O.startsWithVowel = ( isVowel(text.FirstOrDefault()) ? 1 : 0 );
O.endsInVowel = ( isVowel(text.LastOrDefault()) ? 1 : 0 );
O.endsInVowelNumber = ( isVowelOrDigit(text.LastOrDefault()) ? 1 : 0 );
O.longestRepeatingChar = maxRepeatingCharCount(text);
O.longestRepeatingVowel = maxRepeatingVowelCount(text);
O.lowerCaseCount = text.Count(Char.IsLower);
O.upperCaseCount = text.Count(Char.IsUpper);
O.upperCasePercent = ( O.letterCount == 0 ? 0 : ((float)O.upperCaseCount) / O.letterCount );
O.letterPercent = ( O.length == 0 ? 0 : ((float)O.letterCount) / O.length );
O.numberPercent = ( O.length == 0 ? 0 : ((float)O.numberCount) / O.length );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment