Advertisement
Guest User

ReplaceTags

a guest
Jan 16th, 2014
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.70 KB | None | 0 0
  1. //(task 5)You are given a text. Write a program that changes the text in all regions surrounded by the tags <upcase> and </upcase> to uppercase. The tags cannot be nested.
  2.  
  3. using System;
  4.  
  5. namespace ReplaceTags
  6. {
  7.     class ReplaceTags
  8.     {
  9.         private const string OPEN_TAG = "<upcase>";
  10.         private const string CLOSE_TAG = "</upcase>";
  11.  
  12.         static void Main()
  13.         {
  14.             string text = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
  15.  
  16.             try
  17.             {
  18.                 Console.WriteLine(UpTheTextInTag(text));
  19.             }
  20.             catch (ArgumentOutOfRangeException)
  21.             {
  22.                 Console.WriteLine("You have unclosed tag in text !!!");
  23.             }
  24.  
  25.         }
  26.  
  27.         static string UpTheTextInTag(string text)
  28.         {
  29.             int openTagIndex = 0;
  30.             int closeTagIndex = 0;
  31.             string updatedText = string.Empty;
  32.  
  33.             if ((openTagIndex = text.IndexOf(OPEN_TAG, closeTagIndex)) < 0)
  34.             {
  35.                 text = text.Replace(CLOSE_TAG, String.Empty);
  36.                 return text;
  37.             }
  38.             else
  39.             {
  40.                 closeTagIndex = text.IndexOf(CLOSE_TAG, openTagIndex);
  41.  
  42.                 if (closeTagIndex < 0)
  43.                 {
  44.                     throw new ArgumentOutOfRangeException();
  45.                 }
  46.  
  47.                 string tmp = text.Substring(openTagIndex + OPEN_TAG.Length, closeTagIndex - openTagIndex - OPEN_TAG.Length);
  48.                 updatedText = text.Replace(OPEN_TAG + tmp + CLOSE_TAG, tmp.ToUpper());
  49.  
  50.                 return UpTheTextInTag(updatedText);
  51.             }
  52.         }
  53.  
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement