Advertisement
NastySwipy

Fundamentals Exam 03. Anonymous Vox - 05 Nov 2017 Part II

Jun 22nd, 2018
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.32 KB | None | 0 0
  1. namespace _02._AnonymousVox
  2. {
  3.     using System;
  4.     using System.Text.RegularExpressions;
  5.    
  6.     class AnonymousVox
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             //Read the text
  11.             string text = Console.ReadLine();
  12.             //Read the placeholders
  13.             string[] placeholders = Console.ReadLine().Split(new char[] {'{', '}'}, StringSplitOptions.RemoveEmptyEntries);
  14.  
  15.             //Why this pattern? Because we have a sequence of letters, then we have a sequence
  16.             //of ANY ASCII character, then we have another sequence of letters WHICH MUST BE EQUAL TO THE FIRST
  17.             //Well ... How do we do that with Regex? A simple backreference.
  18.             //What's a backreference? Regex Presentation - "\number – matches the value of a numbered capture group"
  19.             //THE VALUE, not the pattern, so its MATCHES THE SAME VALUE THAT THE FIRST GROUP MATCHES
  20.             //Which is exactly what we need for our problem.
  21.             string pattern = @"([a-zA-Z]+)(.+)\1";
  22.             Regex regex = new Regex(pattern);
  23.  
  24.             //Match them all
  25.             MatchCollection matches = regex.Matches(text);
  26.  
  27.             //We'll need to follow the placeholders with some index
  28.             int placeholderIndex = 0;
  29.  
  30.             //Foreach the matches
  31.             foreach (Match match in matches)
  32.             {
  33.  
  34.                 //If the placeholders are more than the values, then we break.
  35.                 if (placeholderIndex >= placeholders.Length) break;
  36.                
  37.                 //If not, we REPLACE FIRST, wait ... Why first. Because we need to replace ONLY ONE PLACEHOLDER WITH ONE VALUE.
  38.                 text = ReplaceFirst(text, match.Groups[2].Value, placeholders[placeholderIndex++]);
  39.             }
  40.  
  41.             Console.WriteLine(text);
  42.         }
  43.  
  44.         //A method for replacing first, works like string.Replace.. But only replaces the first result.
  45.         static string ReplaceFirst(string text, string oldValue, string newValue)
  46.         {
  47.             string substringWithOldValue = text.Substring(0, text.IndexOf(oldValue) + oldValue.Length);
  48.  
  49.             string substringWithNewValue = substringWithOldValue.Replace(oldValue, newValue);
  50.  
  51.             return substringWithNewValue + text.Substring(substringWithOldValue.Length);
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement