问题
Ive been trying to split strings in .NET CF but to no success. If i would have a string like:
Hello
There
World
Then I want each word to be stored in a string array so I can put them individually in my datagrid cell.
Unfortunately, this code I have doesnt seem to remove the New Lines:
string text = _scanResult; //Scan result contains the Hello There World string
string[] lines = text.Split(new Char[] {'\n','\r');
for (int x = 0; x < lines.Length; x++)
{
dt.Rows.Add(lines[x]);
}
dataGrid1.DataSource = dt;
回答1:
Use Environment.NewLine
instead, and use StringSplitOptions.RemoveEmptyEntries
:
string[] lines = text.Split(new string[] {Environment.NewLine},
StringSplitOptions.RemoveEmptyEntries);
回答2:
This is a pretty simple version:
var _scanResult = "foo\r\nbar\r\n";
var lines = System.Text.RegularExpressions.Regex.Split(_scanResult, "\r\n")
.Where(l => !string.IsNullOrEmpty(l));
回答3:
Well, since only characters are accepted as a parameter in String.Split in .NET Compact Framework.
All I had to do was replace the new lines to "\n" character.
Here is the code for some people that might bump into the same problem in the future.
string text = stringWithNewLines;
text = text.Replace(Environment.NewLine,"\n");
string[] lines = text.Split(new Char[] { '\n' });
for (int x = 0; x < lines.Length; x++)
{
if (!String.IsNullOrEmpty(lines[x]))
{
dt.Rows.Add(lines[x]); //Add each string to datatable rows for use in datagrid
}
}
来源:https://stackoverflow.com/questions/13310351/string-split-newlines-in-net-cf