" as albert asked Anna, an antelope appeared!" is considered to be one.
private static bool IsAnAlliteration(string subject)
{
bool result = true;
char lead = default(char);
bool inWord = false;
foreach (char c in subject)
{
char current = char.ToLower(c);
bool isLetter = char.IsLetter(current);
// lead contains first character in string
// all words should start with lead character
if (lead == default(char) && isLetter)
lead = current;
if (!inWord && isLetter && lead != current)
result = false; // start of new word, but does not start with lead char
else if (!inWord && isLetter && lead == current)
inWord = true; // start of new word starts with lead char
else if (inWord && char.IsWhiteSpace(current))
inWord = false; // end of word found
if (!result)
break;
}
// did we find at least one word
result &= (lead != default(char));
return result;
}
2 comments:
Surely an opportunity for some Linq...
public bool IsAlliterative(String s)
{
return new Regex("[^\\w+]").Split(s).Where(a => a.Length > 0).All(a => a.ToLower().StartsWith("" + Char.ToLower(s.First())));
}
@Inigo - nice, though I guess that using you could just do it using a Regex with captures..
Linq+RegExp - who needs anything else ;-0
Post a Comment