Advertisement
Guest User

Strings and Text Processing - 13

a guest
Feb 2nd, 2013
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// Write a program that reverses the words in given sentence.
  2. /// Example: "C# is not C++, not PHP and not Delphi!"  "Delphi not and PHP, not C++ not is C#!".
  3.  
  4.  
  5. using System;
  6. using System.Text;
  7.  
  8. class zad13
  9. {
  10.     static void Main()
  11.     {
  12.         string text = "C# is , , not C++, not . . .  PHP and not Delphi!";
  13.         char[] separators = new char[] { '!', '.', ',', ' ', };
  14.         string[] words = text.Split(separators, StringSplitOptions.RemoveEmptyEntries);
  15.         string[] wordsWith = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  16.  
  17.         Array.Reverse(words);
  18.  
  19.         int wordsWithIndex = 0;
  20.         for (int i = 0; i < words.Length; i++)
  21.         {
  22.             // get last char
  23.             string temp = wordsWith[wordsWithIndex];
  24.             char symbol = temp[temp.Length - 1];
  25.  
  26.             if ((symbol == '!' || symbol == ',' || symbol == '.') && temp.Length > 1)
  27.             {
  28.                 wordsWith[wordsWithIndex] = wordsWith[wordsWithIndex].Remove(0, wordsWith[wordsWithIndex].Length - 1);
  29.                 wordsWith[wordsWithIndex] = words[i] + wordsWith[wordsWithIndex];    
  30.             }
  31.             else if (temp.Length > 1) // skip floating symbols
  32.             {
  33.                 wordsWith[wordsWithIndex] = words[i];
  34.             }
  35.             else
  36.             {
  37.                 i--;
  38.             }
  39.             wordsWithIndex++;
  40.         }
  41.  
  42.         StringBuilder newStr = new StringBuilder();
  43.         for (int i = 0; i < wordsWith.Length; i++)
  44.         {
  45.             newStr.Append(wordsWith[i] + " ");
  46.         }
  47.  
  48.         Console.WriteLine(newStr);
  49.     }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement