String.Split Newlines in .Net CF

杀马特。学长 韩版系。学妹 提交于 2019-12-11 14:35:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!