Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program to reverse the letters of all uppercase words in a text. In case an uppercase word stays unchanged after reversing its letters, then double each of its letters. A word is a sequence of Latin letters separated by non-letter characters (e.g. punctuation characters or digits).
- * The output should hold the result text. Ensure you escape correctly the HTML special characters in the output with the SecurityElement.Escape() method. */
- namespace _15.Uppercase_Words
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Security;
- using System.Text.RegularExpressions;
- class UppercaseWords
- {
- static void Main(string[] args)
- {
- string textLine = Console.ReadLine();
- while (textLine != "END")
- {
- ReverseAndReplaceUppercaseWords(textLine);
- textLine = Console.ReadLine();
- }
- }
- private static void ReverseAndReplaceUppercaseWords(string text)
- {
- const string pattern = @"(?:^|\W)\b[A-Z]+\d*[A-Z]*\b";
- string resultText = text;
- HashSet<string> matchedWords = new HashSet<string>();
- MatchCollection matches = Regex.Matches(text, pattern);
- foreach (Match match in matches)
- {
- string word = match.Groups[0].Value;
- if (matchedWords.Contains(word))
- {
- continue;
- }
- matchedWords.Add(word);
- Dictionary<string, string> matchedGroups = new Dictionary<string, string>();
- MatchCollection uppercases = Regex.Matches(word, @"[A-Z]+");
- foreach (Match uppercase in uppercases)
- {
- string upperWord = uppercase.Groups[0].Value;
- if (matchedGroups.ContainsKey(upperWord))
- {
- continue;
- }
- char[] letters = upperWord.ToCharArray();
- Array.Reverse(letters);
- string reversed = new string(letters);
- if (reversed == upperWord)
- {
- char[] doubleReverse = new char[reversed.Length * 2];
- for (int i = 0; i < reversed.Length; i++)
- {
- doubleReverse[2 * i] = reversed[i];
- doubleReverse[2 * i + 1] = reversed[i];
- }
- reversed = new string(doubleReverse);
- }
- matchedGroups.Add(upperWord, reversed);
- }
- string replacement = matchedGroups
- .Aggregate(word, (current, @group) => current.Replace(@group.Key, @group.Value));
- resultText = resultText.Replace(word, replacement);
- }
- Console.WriteLine(SecurityElement.Escape(resultText));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement