Click here to Skip to main content
15,904,153 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
a C# program to reverses each word in a sentence except these punctuation marks (? ! . ,)

example: (input) this is john, who are you?

(output) sith si nhon, ohw era uoy?
_______________________________________...
here's my code which reverses punctuation marks too and removes the space character in the output.. :,(

C#
string str = Console.ReadLine(); 
string strrev = ""; 

foreach (var word in str.Split(' ')) 
{ 
   string temp = ""; 
   foreach (var ch in word.ToCharArray()) 
   { 
      temp = ch + temp; 
   } 
   strrev = strrev + temp + ""; 
} 
Console.WriteLine(strrev);
Console.ReadLine();
Posted
Updated 12-Apr-14 9:14am
v3
Comments
PIEBALDconsult 12-Apr-14 13:43pm    
Split is too limiting, it's not very useful. Try a RegularExpression.
Also, the ToCharArray is needless, you can foreach the string characters directly.
[no name] 12-Apr-14 13:47pm    
And nowhere are you checking to see if the char is a punctuation mark.

Further to Solution 1 (and shamelessly stealing Maciej Los' delimiters) here's how I went about it
C#
string str = "this is john, who are you?";
string strrev = "";
char[] punctuation = new char[] { ' ', ',', '.', ':', '\t', '?', '!', '@', '#' };   // note the space!

// convert the input to char[]
char[] inputAsChars = str.ToCharArray();

// step through the char[] looking for punctuation and spaces
string temp = "";
foreach (char c in inputAsChars)
{
    if (punctuation.Contains(c))
    {
        //found a word separator so reverse what we have so far
        char[] tx = temp.ToCharArray();
        Array.Reverse(tx);
        temp = new string(tx);
        strrev += temp + c;    // make sure we add on the separator
        temp = "";
    }
    else
        temp += c; //otherwise add the char to the end of our temporary word
}

System.Diagnostics.Debug.Print(strrev);


Produced this output
siht si nhoj, ohw era uoy?
 
Share this answer
 
You are almost at target ;)

Have a look here: How to: Split Strings (C# Programming Guide)[^]
As you see, Split() function can accept many delimiters:
C#
char[] delimiterChars = { ' ', ',', '.', ':', '\t', '?', '!', '@', '#'};


Tip: after second forach loop, replace this line:
C#
strrev = strrev + temp + ""; 

with:
C#
strrev = strrev + temp + " "; 



That's all!
 
Share this answer
 
Comments
CHill60 12-Apr-14 14:23pm    
4'd only (sorry!) - when I tried this the punctuation was removed.
Maciej Los 12-Apr-14 14:25pm    
Not to worry...
Thank you, Chill ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900