Skip to content

Instantly share code, notes, and snippets.

@Danielkaas94
Created February 1, 2018 14:49
Show Gist options
  • Save Danielkaas94/1e9204245215cc02036a48bc83cda4e8 to your computer and use it in GitHub Desktop.
Save Danielkaas94/1e9204245215cc02036a48bc83cda4e8 to your computer and use it in GitHub Desktop.
AlphabetPosition "The sunset sets at twelve o' clock." => "20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11" as a string
/// <summary>
/// Replace every letter with its position in the alphabet.
/// If anything in the text isn't a letter, ignore it and don't return it.
/// A being 1, B being 2, etc.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string AlphabetPosition(string text)
{
int index;
StringBuilder sB = new StringBuilder();
// Replace everything that is not (^) a word character (\w), a digit (\d) or whitespace (\s) with an empty string.
string stringWithoutSpecialCharacters = Regex.Replace(text, @"[^\w\d\s]", "");
foreach (char item in stringWithoutSpecialCharacters)
{
index = char.ToUpper(item) - 64;
if (index > 0 && index <= 30)
{
sB.Append(index);
sB.Append(" ");
}
}
return sB.ToString().TrimEnd();
}
/// <summary>
/// Same as AlphabetPosition, just in one line.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string AlphabetPosition2(string text)
{
return string.Join(" ", text.ToLower().Where(char.IsLetter).Select(x => x - 'a' + 1));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment