Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class MakeUppercaseTextSurroundedByTags
- {
- //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. Example:
- //We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.
- //The expected result:
- //We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.
- static List<int> FindInTextIndices(string text, string substrToSearch)//Returns a list with the indices of the searchhed substring in a text
- {
- List<int> tagsPositions = new List<int>();
- int lastSubstrFoundIndex = text.LastIndexOf(substrToSearch);
- for (int index = 0; index < lastSubstrFoundIndex; )
- {
- index = text.ToLowerInvariant().IndexOf(substrToSearch, index);
- tagsPositions.Add(index);
- index += substrToSearch.Length;
- }
- return tagsPositions;
- }
- static string MakeUppercaseSubstring(string text, List<int> startIndices, List<int> endIndices)//Makes the text between the tags Uppercase
- {
- for (int i = 0; i < startIndices.Count; i++)
- {
- string substring = text.Substring(startIndices[i], endIndices[i] - startIndices[i] + 1).ToUpper();
- text = text.Replace((text.Substring(startIndices[i], endIndices[i] - startIndices[i] + 1)), substring);
- }
- return text;
- }
- static string RemoveTags(string text, string tag, List <int> tagIndices)//Removes the tags from the text
- {
- for (int index = tagIndices.Count-1; index >=0; index--)
- {
- text = text.Remove(tagIndices[index], tag.Length);
- }
- return text;
- }
- static void Main()
- {
- string text = "We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else.";
- string openingTag = "<upcase>",
- closingTag = "</upcase>";
- List<int> openingTagIndices = FindInTextIndices(text,openingTag);//Find the indices of the opening tag
- List<int> closingTagIndices = FindInTextIndices(text, closingTag);//Find the indices of the closing tag
- if (openingTagIndices == null || closingTagIndices == null)//If one of the arrays is null
- {
- Console.WriteLine("At least one of the tags haven't been found in the text!");
- }
- else
- {
- string result = MakeUppercaseSubstring(text, openingTagIndices, closingTagIndices);//Make uppercase the text between the tags
- result = RemoveTags(result, openingTag, openingTagIndices);//Remove the opening tags
- closingTagIndices.Clear();//Clear the array with the end tag indices because they have changed
- closingTagIndices = FindInTextIndices(result, closingTag);//Find the new indices of the closing tags
- result = RemoveTags(result, closingTag, closingTagIndices);//Remove the closing tags
- Console.WriteLine(result);//Print the result
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement