Is there a ReadWord () method in the .NET Framework?
I would hate to reinvent something that has already been written, so I wonder if there is a ReadWord () function somewhere in the .NET Framework that fetches words based on some text delimited by whitespace and line breaks.
If not, do you have an implementation that you want to share?
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);
}
a source to share
Not that I knew about him directly. If you don't mind having them all in one go, you can use a regex:
Regex wordSplitter = new Regex(@"\W+");
string[] words = wordSplitter.Split(data);
If you have leading / trailing white space, you will get a blank line at the start or end, but you can always call first Trim
.
Another option is to write a method that reads the word based TextReader
. It might even be an extension method if you are using .NET 3.5. Implementation example:
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);
}
}
}
}
Output:
'Four'
'score'
'and'
'seven'
'years'
'ago'
a source to share
Not as such, however you can use String.Split to split a string into an array of strings based on the delimiter character or string. You can also specify multiple lines / characters to separate.
If you prefer to do this without loading everything into memory, you can write your own stream class that does this when it reads from the stream, but the above is a quick fix for a little bit of data word splitting.
a source to share