C# 如何检查流线中是否有4个或更多空格
我试图在文本文件中为管道重新放置空间,但如果有4个或更多空间。到目前为止,我的代码是:C# 如何检查流线中是否有4个或更多空格,c#,char,streamreader,C#,Char,Streamreader,我试图在文本文件中为管道重新放置空间,但如果有4个或更多空间。到目前为止,我的代码是: string MyNewFile; using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1)) { using (StreamReader sReplaceReader = new StreamReader(myFile)) { string line, textLine = ""
string MyNewFile;
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
using (StreamReader sReplaceReader = new StreamReader(myFile))
{
string line, textLine = "";
while ((line = sReplaceReader.ReadLine()) != null)
{
if (line.Contains(" ")>=4 )//if contains 4 or more spaces
{
textLine = line.Replace(" ", "|");
}
sWriter.WriteLine(textLine);
}
}
}
我的想法是通过方法中的参数获得空格数,但我不知道如何放置类似line.Replace(4.space或4 char.IsWhiteSpace(),separator)的内容。我希望你已经向我解释清楚了正则表达式是一个很好的工作工具。试试这个:
string MyNewFile;
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
using (StreamReader sReplaceReader = new StreamReader(myFile))
{
string line, textLine = "";
while ((line = sReplaceReader.ReadLine()) != null)
{
RegexOptions options = RegexOptions.None;
Regex regex = new Regex("[ ]{4,}", options);
string textLine = regex.Replace(line, "|");
sWriter.WriteLine(textLine);
}
}
}
这是一个与这里的答案非常相似的解决方案:您可以使用
RegEx
来执行此操作,并且可以创建一个接受变量输入的方法(因此您可以指定要替换的字符和最小连续实例数,以及替换字符串:
public static string ReplaceConsecutiveCharacters(string input, char search,
int minConsecutiveCount, string replace)
{
return input == null
? null
: new Regex($"[{search}]{{{minConsecutiveCount},}}", RegexOptions.None)
.Replace(input, replace);
}
然后可以这样称呼它:
static void Main()
{
var testStrings = new List<string>
{
"Has spaces scattered throughout the body .",
" starts with spaces and ends with spaces "
};
foreach (var testString in testStrings)
{
var result = ReplaceConsecutiveCharacters(testString, ' ', 4, "|");
Console.WriteLine($"'{testString}' => '{result}'");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
static void Main()
{
var testStrings=新列表
{
“身体上到处都是空间。”,
“以空格开始,以空格结束”
};
foreach(testStrings中的var testString)
{
var result=replaceConsutiveCharacters(testString,,,4,,,,,“|”);
WriteLine($“{testString}'=>”{result}');
}
GetKeyFromUser(“\n完成!按任意键退出…”);
}
输出
我的想法是通过方法中的参数获得空格数,但我不知道如何放置类似line.Replace(4.space或4 char.IsWhiteSpace(),separator)的内容
可以这样称呼:
string MyNewFile = "...";
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
foreach(string line in File.ReadLines(myFile))
{
sWriter.WriteLine(SpacesToDelimiter(line));
}
}
您是在寻找4个或更多的连续空格,还是在任何地方寻找4个或更多的空格?@gregdorian将该行作为参数传递给function@gregdorian但是考虑到问题中的初始代码,我将使用
File.ReadLines()
而不是streamreader。现在我的答案中显示了这一点。SpaceToDelimiter方法缺少char参数。:)。。那么,把它加起来。。?
string MyNewFile = "...";
using (StreamWriter sWriter = new StreamWriter(MyNewFile, false, encoding, 1))
{
foreach(string line in File.ReadLines(myFile))
{
sWriter.WriteLine(SpacesToDelimiter(line));
}
}