Reputation: 6849
I have searched lot of questions and answers but, I just got lengthy and complicated expressions. Now I want to replace all white spaces from the string. I know it can be done by regex. but, I don't have enough knowledge about regex and how to replace all white space with ','(comma) using it. I have checked some links but, I didn't get exact answer. If you have any link of posted question or answer like this. please suggest me.
My string is defined as below.
string sText = "BankMaster AccountNo decimal To varchar";
and the result should be return as below.
"BankMaster,AccountNo,decimal,To,varchar"
Full Code:
string sItems = Clipboard.GetText();
string[] lines = sItems.Split('\n');
for (int iLine =0; iLine<lines.Length;iLine++)
{
string sLine = lines[iLine];
sLine = //CODE TO REPLACE WHITE SPACE WITH ','
string[] cells = sLine.Split(',');
grdGrid.Rows.Add(iLine, cells[0], cells[1], cells[2], cells[4]);
}
Additional Details
I have more than 16000 line in a list. and all lines are same formatted like given example above. So, I am going to use regular expression instead of loop and recursive function call. If you have any other way to make this process more faster than regex then please suggest me.
Upvotes: 6
Views: 34660
Reputation: 26209
Try This:
string str = "BankMaster AccountNo decimal To varchar";
StringBuilder temp = new StringBuilder();
str=str.Trim(); //trim before logic to avoid any trailing/leading whitespaces.
foreach(char ch in str)
{
if (ch == ' ' && temp[temp.Length-1] != ',')
{
temp.Append(",");
}
else if (ch != ' ')
{
temp.Append(ch.ToString());
}
}
Console.WriteLine(temp);
Output:
BankMaster,AccountNo,decimal,To,varchar
Upvotes: 0
Reputation: 834
there are lot's of samples to do that by regular expressions:
Flex: replace all spaces with comma,
Regex replace all commas with value,
http://www.perlmonks.org/?node_id=896548,
http://www.dslreports.com/forum/r20971008-sed-help-whitespace-to-comma
Upvotes: 0
Reputation: 26921
string result = Regex.Replace(sText, "\\s+", ",");
\s+
stands for "capture all sequential whitespaces of any kind".
By whitespace regex engine undeerstands space (), tab (
\t
), newline (\n
) and caret return (\r
)
Upvotes: 13
Reputation: 7290
string a = "Some text with spaces";
Regex rgx = new Regex("\\s+");
string result = rgx.Replace(a, ",");
Console.WriteLine(result);
The code above will replace all the white spaces with ',' character
Upvotes: 1