i trying code function reverse words in string in c#, ex: "this text, hello world"
should printed "world hello, text this" number of white spaces must same in reverse string , special characters comma must correctly placed after preceding word shown in reverse string. tried following, not taking care of special characters ','
public static string reversestr(string s) { string result = ""; string word = ""; foreach (char c in s) { if (c == ' ') { result = word + ' ' + result; word= ""; } else { word = word + c; } } result = word + ' ' + result; return result; }
what mean
with special characters comma
are there other characters need treated different? turns "this text, hello world"
expected result "world hello, text this"
string input = "this text, hello world"; string result = string.join(" ", input.split(' ', ',').reverse()).replace(" ", ", ");
update
if want treat every special character, need regex solution.
string result2 =string.join(string.empty, system.text.regularexpressions.regex.split(input, @"([^\w]+)").reverse());