c# - 如何每n个单词插入一个字符串?
问题描述
我需要文字方面的帮助。我得到了一个代码,例如查找该行是否有偶数个单词,然后它会查找文本文件中的每个第二个单词。问题是我不知道如何在每个第二个单词上附加一个字符串并将其打印出来。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.IO;
namespace sd
{
class Program
{
const string CFd = "..\\..\\A.txt";
const string CFr = "..\\..\\Rezults.txt";
static void Main(string[] args)
{
Apdoroti(CFd, CFr);
Console.WriteLine();
}
static void Apdoroti(string fd, string fr)
{
string[] lines = File.ReadAllLines(fd, Encoding.GetEncoding(1257));
using (var far = File.CreateText(fr))
{
StringBuilder news = new StringBuilder();
VD(CFd,news);
far.WriteLine(news);
}
}
static void VD(string fv, StringBuilder news)
{
using (StreamReader reader = new StreamReader(fv,
Encoding.GetEncoding(1257)))
{
string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
int nrl;
int prad = 1;
foreach (string line in lines)
{
nrl = line.Trim().Split(' ').Count();
string[] parts = line.Split(' ');
if (nrl % 2 == 0)
{
Console.WriteLine(nrl);
for (int i = 0; i < nrl; i += 2)
{
int ind = line.IndexOf(parts[i]);
nauja.Append(parts[i]);
Console.WriteLine(" {0} ", news);
}
}
}
}
}
}
}
例如,如果我收到这样的文字:“丛林中的怪物从前,丛林中生活着一只聪明的狮子。他总是因其智慧和善良而受到尊重。”
然后它应该打印出:“Monster in abb the Jungle abb 从前 abb 从前 abb 一只聪明的 abb 狮子生活在丛林中。他一直因其智慧和善良而受到尊重。”
解决方案
您可以使用正则表达式替换来做到这一点,就像这个正则表达式:
@"\w+\s\w+\s"
它可以匹配 a Word
、 a Space
、 aWord
和 a Space
。
现在将其替换为:
"$&abb "
如何使用:
using System.Text.RegularExpressions;
string text = "Monster in the Jungle Once upon a time a wise lion lived in jungle. He was always respected for his intelligence and kindness.";
Regex regex = new Regex(@"\w+\s\w+\s");
string output = regex.Replace(text, "$&abb ");
现在您将获得所需的输出。
编辑:
要使用任意数量的单词,您可以使用:
@"(\w+\s){3}"
其中量词 ( here 3
) 可以设置为您想要的任何值。
编辑2:
如果您不想替换数字:
@"([a-zA-Z]+\s){2}"
推荐阅读
- java - 创建名为“tilesViewResolver”的 bean 时出错
- docker - Docker覆盖网络,端口连接不在netstat中可见
- python - 如何在 Mac 中将 .py 转换为 .exe
- django - 如何在返回重定向中获取 pk 参数
- autodesk-forge - 使用 Forge Viewer 6.5.2 获取无效的投影矩阵和隐藏的自定义 THREE.js 对象
- airflow - 气流糟糕页面
- javascript - 从下拉列表中单击后量角器不会转到下一行
- php - 左连接两个表并获取第二个表中的记录数
- c# - 如何从 TFS 查询指定工作项的所有修订?
- python - 使用 Python 从 Outlook 中提取电子邮件