【问题标题】:Is there a ReadWord() method in the .NET Framework?.NET Framework 中是否有 ReadWord() 方法?
【发布时间】:2009-05-14 20:45:43
【问题描述】:

我不想重新发明已经写好的东西,所以我想知道 .NET 框架中是否有一个 ReadWord() 函数可以提取基于由空格和换行符分隔的一些文本的单词。

如果没有,您有想要分享的实现吗?

string data = "Four score and seven years ago";
List<string> words = new List<string>();
WordReader reader = new WordReader(data);

while (true)
{
   string word =reader.ReadWord();
   if (string.IsNullOrEmpty(word)) return;
   //additional parsing logic goes here
   words.Add(word);
}

【问题讨论】:

    标签: c# .net parsing text


    【解决方案1】:

    不是我直接知道的。如果您不介意一次性获取所有内容,可以使用正则表达式:

    Regex wordSplitter = new Regex(@"\W+");
    string[] words = wordSplitter.Split(data);
    

    如果你有前导/尾随空格,你会在开头或结尾得到一个空字符串,但你总是可以先调用Trim

    另一种选择是编写一个基于TextReader 读取单词的方法。如果您使用的是 .NET 3.5,它甚至可能是一种扩展方法。示例实现:

    using System;
    using System.IO;
    using System.Text;
    
    public static class Extensions
    {
        public static string ReadWord(this TextReader reader)
        {
            StringBuilder builder = new StringBuilder();
            int c;
    
            // Ignore any trailing whitespace from previous reads            
            while ((c = reader.Read()) != -1)
            {
                if (!char.IsWhiteSpace((char) c))
                {
                    break;
                }
            }
            // Finished?
            if (c == -1)
            {
                return null;
            }
    
            builder.Append((char) c);
            while ((c = reader.Read()) != -1)
            {
                if (char.IsWhiteSpace((char) c))
                {
                    break;
                }
                builder.Append((char) c);
            }
            return builder.ToString();
        }
    }
    
    public class Test
    {
        static void Main()
        {
            // Give it a few challenges :)
            string data = @"Four score     and
    
    seven years ago    ";
    
            using (TextReader reader = new StringReader(data))
            {
                string word;
    
                while ((word = reader.ReadWord()) != null)
                {
                    Console.WriteLine("'{0}'", word);
                }
            }
        }
    }
    

    输出:

    'Four'
    'score'
    'and'
    'seven'
    'years'
    'ago'
    

    【讨论】:

      【解决方案2】:

      不是这样,但是您可以使用 String.Split 根据分隔字符或字符串将字符串拆分为字符串数组。您还可以为拆分指定多个字符串/字符。

      如果您希望在不将所有内容加载到内存的情况下执行此操作,那么您可以编写自己的流类,在从流中读取时执行此操作,但以上是少量数据分词的快速修复。

      【讨论】:

        猜你喜欢
        • 2012-12-09
        • 2010-12-12
        • 2011-06-28
        • 2019-07-22
        • 1970-01-01
        • 2014-02-06
        • 2022-12-04
        • 2021-11-22
        • 1970-01-01
        相关资源
        最近更新 更多