0

如何从文本文件中读取仅包含一两个字符的数字。例如:

123 32 40 14124 491 1

我需要得到 :32 40 1

我做了什么:

OpenFileDialog ls = new OpenFileDialog();
int numbersFromFile;
if (ls.ShowDialog() == DialogResult.OK)
{
    StreamReader read = new StreamReader(ls.FileName);
}

我不确定该怎么做,我想我需要读取字符串中的所有字符然后使用子字符串功能?

4

4 回答 4

0

你可以使用类似的东西:

string lines = File.ReadAllText(ls.FileName);
string[] words = lines.Split(new[] {' ', '\n'}, StringSplitOptions.RemoveEmptyEntries);
string result = String.Join(" ", words.Where(w => w.Length < 3));

// result == "32 40 1" given above input
于 2012-10-01T20:37:46.070 回答
0
string numbers = string.Empty;
using (var reader = new StreamReader(@"C:\Temp\so.txt"))
{
    numbers = reader.ReadToEnd();
}

var matches = numbers.Split(' ').Where(s => s.Length == 1 || s.Length == 2);
foreach (var match in matches)
{
    Console.WriteLine(match);
}

matches将包含一个IEnumerable<string>长度为 1 或 2 的字符串。不过,这不会检查它是否是字符串,但可以轻松更改代码来执行此操作。

于 2012-10-01T20:42:59.860 回答
0

您可以将内容读入一个字符串,然后拆分单词以测试长度。像下面

            //create the Stream reader object
            StreamReader sr = new StreamReader("FilePath");
            //open and get the contents put into a string
            String documentText = sr.ReadToEnd();
            //close the reader
            sr.Close();
            //split out the text so we can look at each word
            String[] textStrings = documentText.Split(' ');
            //create a list to hold the results
            List<String> wordList = new List<String>();

            //loop through the words and check the length
            foreach (String word in textStrings)
            {   //if it is less then 3 add to our list
                if (word.Length < 3)
                {
                    wordList.Add(word);
                }
            }


            //...do what you need to with the results in the list
            foreach (String wordMatch in wordList)
            {
                MessageBox.Show("There are " + wordList.Count.ToString() + " items in the list");
            }
于 2012-10-01T20:43:21.233 回答
0

我只是用一个简单的正则表达式来做到这一点;

string strRegex = @"(?<=\ )\d{1,2}(?!\d)";
RegexOptions myRegexOptions = RegexOptions.Multiline;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"123 32 40 14124 491 1"; // read.ReadToEnd();

foreach (Match myMatch in myRegex.Matches(strTargetString))
{
  if (myMatch.Success)
  {
    // Add your code here
  }
}

(?) 构造确保您的匹配项周围有一个空格和非数字,并且 \d{1,2} 匹配一组长度为一个或两个字符的数字。

于 2012-10-01T20:43:56.830 回答