c# - .NET Framework中是否有ReadWord()方法?

标签 c# .net parsing text

我不想重新发明已经编写的内容,所以我想知道.NET Framework中是否存在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);
}

最佳答案

并非我直接知道。如果您不介意一次性使用它们,则可以使用正则表达式:

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'

关于c# - .NET Framework中是否有ReadWord()方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/865661/

相关文章:

c# - 与 MySQL 连接的 NullReferenceException

c# - 如何在 C# 中创建 NVarchar(max) Sqlparameter?

c# - DirectX 9、10 Hook 以在全屏游戏上覆盖内容

c# - WCF 服务超时,然后执行操作?

c# - c++ 中的 string* [] 转换为 c# 中的 string[]

c# - 获取实体表名称 - EF7

.net - 基准 XSLT 性能

java - 是否有提供 LDAP 样式解析的独立 Java 库?

java - 我需要一个工具来解析 Lua 表,最好是用 Ruby 或 Java

c# - 需要为 C# 代码构建 XML 表示