日期:2014-05-18  浏览次数:20884 次

C# 用空格分隔字符串,这么简单怎么会出错呢?初学者请教。
代码如下:
  StreamReader my_stream_reader = new StreamReader("results.txt");
  string getligne = my_stream_reader.ReadLine();
  while (getligne.Contains(" "))
  {  
  getligne = getligne.Replace(" ", " ");
  }
  string[] sArray = getligne.Split(' ');
  MessageBox.Show(sArray[0], "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);

results.txt中是如下的文件:
18 18 18 18 18 18 18 18 18 18 18

18.143 18.146 18.2 18.1788 18.1808 18.179 18.179 18.2 18.1836 18.1854 18.2

可是结果还是第一行字符串,根本没有分隔成功。请指教。。

------解决方案--------------------
if (getligne.Contains(" "))
{
getligne = getligne.Replace(" ", " ");
}

这样试试?
------解决方案--------------------
string[] sArray = getligne.SpSplit(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
------解决方案--------------------
C# code

            StreamReader my_stream_reader = new StreamReader(@"E:\test.txt");
            string getligne = my_stream_reader.ReadToEnd().ToString();
            if (getligne.Contains(" "))
            {
                getligne = getligne.Replace(" ", " ");
            }
            string[] sArray = getligne.Split(' ');

            foreach (string s in sArray)
                Console.WriteLine(s);

------解决方案--------------------
探讨
情况不妙,改进代码后为:
StreamReader my_stream_reader = new StreamReader("results.txt");
string getligne = my_stream_reader.ReadLine().ToString();
if (getligne.Contains(" "))
{
getligne = getligne……

------解决方案--------------------
List<string> lst=new List<string>(File.ReadAllLines(""))
foreach(string s in lst)
{
string[] arr= s.Split(new string[]{" ","\r\n"},StringSplitOptions.RemoveEmptyEntries);
}