Skip to content

Instantly share code, notes, and snippets.

@Filkolev
Created May 27, 2015 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Filkolev/39ca75ad88b3a929f20b to your computer and use it in GitHub Desktop.
Save Filkolev/39ca75ad88b3a929f20b to your computer and use it in GitHub Desktop.
Uppercase Words
using System;
using System.Linq;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
public class UppercaseWords
{
public static void Main()
{
const string UppercaseWordPattern = @"(?<![a-zA-Z])[A-Z]+(?![a-zA-Z])";
Regex regex = new Regex(UppercaseWordPattern);
string input = Console.ReadLine();
while (input != "END")
{
var words = regex.Matches(input);
foreach (Match match in words)
{
string word = match.ToString();
int index = match.Index;
var replacement = IsPalindrome(word) ? GetRepeatedWord(word) : GetReversedWord(word);
Regex replacementRegex = new Regex(word);
input = replacementRegex.Replace(input, replacement, 1, index);
}
Console.WriteLine(SecurityElement.Escape(input));
input = Console.ReadLine();
}
}
private static string GetReversedWord(string word)
{
return new string(word.ToCharArray().Reverse().ToArray());
}
private static string GetRepeatedWord(string word)
{
StringBuilder result = new StringBuilder(2 * word.Length);
foreach (var symbol in word)
{
result.AppendFormat("{0}{0}", symbol);
}
return result.ToString();
}
private static bool IsPalindrome(string word)
{
string reversedWord = GetReversedWord(word);
return reversedWord == word;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment