FWIW, StringBuilder is not necessary, although this example which i've tested in LINQPad v4.42.01 does use StringBuilder:
public static String spacesBeGone(Char placeHolder, String stringToCompact)
{
List<Char> compactedStringProxy = new List<Char>();
Boolean compressingSpaces = true;
foreach (Char thisChar in stringToCompact)
{
switch (thisChar)
{
case ' ': if (!compressingSpaces)
{
compressingSpaces = true;
compactedStringProxy.Add(placeHolder);
}
break;
default: compressingSpaces = false;
compactedStringProxy.Add(thisChar);
break;
}
}
StringBuilder compactedString = new StringBuilder();
foreach (Char proxyChar in compactedStringProxy)
{
compactedString.Append(proxyChar);
}
return compactedString.ToString();
}
test
void Main()
{
Console.WriteLine (spacesBeGone('%', "Mr John Smith"));
Console.WriteLine (spacesBeGone('%', "Mr John Smith"));
Console.WriteLine (spacesBeGone('¿', @"Hi, I am trying to convert space in a string into other characters. For example: input: ""Mr John Smith"" ouput ""Mr%John%Smith"". We need StringBuilder ? Please advise."));
}
B-) Please help me by completing my school survey about computer programmers on my website. Thank you!!! Gerry Lowry +1 705-429-7550 wasaga beach, ontario, canada
gerrylowry
All-Star
20513 Points
5712 Posts
Re: how can I replace space with other signs
May 03, 2012 05:31 AM|LINK
@ sdnd2000
TIMTOWTDI =. there is more than one way to do it
FWIW, StringBuilder is not necessary, although this example which i've tested in LINQPad v4.42.01 does use StringBuilder:
public static String spacesBeGone(Char placeHolder, String stringToCompact) { List<Char> compactedStringProxy = new List<Char>(); Boolean compressingSpaces = true; foreach (Char thisChar in stringToCompact) { switch (thisChar) { case ' ': if (!compressingSpaces) { compressingSpaces = true; compactedStringProxy.Add(placeHolder); } break; default: compressingSpaces = false; compactedStringProxy.Add(thisChar); break; } } StringBuilder compactedString = new StringBuilder(); foreach (Char proxyChar in compactedStringProxy) { compactedString.Append(proxyChar); } return compactedString.ToString(); }test
void Main() { Console.WriteLine (spacesBeGone('%', "Mr John Smith")); Console.WriteLine (spacesBeGone('%', "Mr John Smith")); Console.WriteLine (spacesBeGone('¿', @"Hi, I am trying to convert space in a string into other characters. For example: input: ""Mr John Smith"" ouput ""Mr%John%Smith"". We need StringBuilder ? Please advise.")); }test output
g.