Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- class ReverseWordsInASentencesKeepPunctuation
- {
- //Write a program that reverses the words in given sentence.
- //Example: "C# is not C++, not PHP and not Delphi!" -> "Delphi not and PHP, not C++ not is C#!".
- static void Main()
- {
- string text = "C# is not C++, not PHP and not Delphi!"; //Text to reverse
- List<string> reversedSentence = new List<string>(); //List that stores the words of the sentence
- List<string> punctuation = new List<string>();//List that stores the punctuation of the sentence
- string word = ""; //temporary string for each word construction
- string separator = "";//temporary string for each punctuation construction (e.g. if you have comma and interval theay should be stored together as ", ")
- foreach (char item in text) //Iterate through the text
- {
- if (char.IsSymbol(item) || char.IsLetterOrDigit(item) || item == '#') //If you have a letter,digit or symbol
- {
- if (separator != "") //if the separator has value
- {
- punctuation.Add(separator);//add it to the punctuation list
- }
- word += item; //construct a word
- separator = ""; //Empty the separator constructor
- }
- else if (char.IsSeparator(item) || char.IsPunctuation(item) || char.IsWhiteSpace(item))//If you have a separator or punctuation
- {
- if (word != "")//if our word has value
- {
- reversedSentence.Add(word);//Add it to the list of words in the sentence that will be reversed
- }
- separator += item;//construct a separator
- word = "";//Empty the word constructor
- }
- }
- if (separator !="")//If we have a separator value left
- {
- punctuation.Add(separator);//add it to the punctuation list
- }
- if (word != "")//If we have a word value left
- {
- reversedSentence.Add(word);//Add it to the list of words
- }
- //Print the output
- int printLength = Math.Max(reversedSentence.Count, punctuation.Count); //Get the list with more elements
- for (int k = 0, i = reversedSentence.Count - 1, j = 0; k < printLength; k++) //Cycle to the length of the longer list (k)
- {
- if (i >= 0)//Check for end of the words list
- {
- Console.Write(reversedSentence[i]);
- i--;
- }
- if (j < punctuation.Count)//Check for end of the punctuation list
- {
- Console.Write(punctuation[j]);
- j++;
- }
- }
- Console.WriteLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement