在C#中,可以使用以下步骤将不同的单词保存到.txt文件中:
using System;
using System.IO;
using System.Text.RegularExpressions;
string inputText = "这是一段文本,包含不同的单词。";
string[] words = Regex.Matches(inputText, @"\b\w+\b")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
using (StreamWriter writer = new StreamWriter("words.txt"))
{
foreach (string word in words)
{
writer.WriteLine(word);
}
}
writer.Close();
完整的代码示例如下:
using System;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string inputText = "这是一段文本,包含不同的单词。";
string[] words = Regex.Matches(inputText, @"\b\w+\b")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
using (StreamWriter writer = new StreamWriter("words.txt"))
{
foreach (string word in words)
{
writer.WriteLine(word);
}
}
}
}
这段代码将会创建一个名为"words.txt"的文本文件,并将提取到的不同单词逐行写入该文件中。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体产品选择应根据实际需求进行评估。
领取专属 10元无门槛券
手把手带您无忧上云