Skip to content

Instantly share code, notes, and snippets.

@valiyo
Last active December 12, 2015 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valiyo/4702634 to your computer and use it in GitHub Desktop.
Save valiyo/4702634 to your computer and use it in GitHub Desktop.
[C#] Домашно Strings and Text Processing - 13 задача Reverce the Words in a Sentence
using System;
using System.Collections.Generic;
/* 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#!". */
class ReverseWordsInSentence
{
static void Main()
{
string input = "C# is not C++, not PHP and not Delphi!";
// Split the words and reverse their order
char[] punctuationMarks = new char[] { ' ', ',', '.', ';', ':', '!', '?', '(', ')'};
string[] words = input.Split(punctuationMarks, StringSplitOptions.RemoveEmptyEntries);
Array.Reverse(words);
// Create a punctuation marks mask
List<char> marksPosition = new List<char>();
foreach (char character in input)
{
switch (character)
{
case ' ': marksPosition.Add(character); break;
case ',': marksPosition.Add(character); break;
case '.': marksPosition.Add(character); break;
case ':': marksPosition.Add(character); break;
case ';': marksPosition.Add(character); break;
case '!': marksPosition.Add(character); break;
case '?': marksPosition.Add(character); break;
case '(': marksPosition.Add(character); break;
case ')': marksPosition.Add(character); break;
default: marksPosition.Add('ж'); break;
}
}
// Replace the word placeholders from the mask with the words in reversed order
// and print them together with the punctuation marks
int countMask = 0;
int countWords = 0;
for (int i = 0; i < marksPosition.Count; i++)
{
if ((marksPosition[i] == 'ж') && (countMask == 0))
{
Console.Write(words[countWords]);
countMask++;
countWords++;
}
else if (marksPosition[i] != 'ж')
{
Console.Write(marksPosition[i]);
countMask = 0;
}
}
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment