C# 交换文本文件中的动态行数
我有很多带有值的文本文件,尽管文本文件中的行应该部分加扰 文本文件的示例如下:(参见编辑以获得更简单的示例) 在C# 交换文本文件中的动态行数,c#,random,C#,Random,我有很多带有值的文本文件,尽管文本文件中的行应该部分加扰 文本文件的示例如下:(参见编辑以获得更简单的示例) 在[RAND]和[/RAND]之间的所有内容都应该按随机顺序排列。 到目前为止,我有以下几点,但我完全不知道如何从这里继续下去,或者这是否是正确的方法 using (StreamReader reader = new StreamReader(LocalFile)) { bool InRegion = false; string line; whi
[RAND]
和[/RAND]
之间的所有内容都应该按随机顺序排列。
到目前为止,我有以下几点,但我完全不知道如何从这里继续下去,或者这是否是正确的方法
using (StreamReader reader = new StreamReader(LocalFile))
{
bool InRegion = false;
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Equals("[RAND]"))
InRegion = true;
if (line.Equals("[/RAND]"))
InRegion = false;
}
}
我担心的一点是,我正在使用StreamReader,因此无法更改文件
在RAND
块中可以有2行,但也可以有10行,每个文件可以有多个RAND
块。
有人能告诉我怎么走吗
先谢谢你
编辑:
更简单的例子:
A
B
C
[RAND]
D
E
F
[/RAND]
G
H
然后,它将以随机顺序用D、E和F对这些行进行置乱,从而得到如下结果:
A
B
C
E
F
D
G
H
导致代码最多(尽管可读性最好)的“笨重”方式是:
- 读取所有行,关闭文件
- 找到要随机化的块
- 将这些块随机化
- 将结果写入新文件
- 将新文件移到旧文件上
var linesInFile = File.ReadAllLines();
var newLines = new List<string>();
var toRandomize = new List<string>();
bool inRegion = false;
for (int i = 0; i < linesInFile.Count; i++)
{
string line = linesInFile[i];
if (line == "[RAND]")
{
inRegion = true;
continue;
}
if (line == "[/RAND]")
{
inRegion = false;
// End of random block.
// Now randomize `toRandomize`, add it to newLines and clear it
newLines.AddRange(toRandomize);
toRandomize.Clear();
continue;
}
if (inRegion)
{
toRandomize.Add(line);
}
else
{
newLines.Add(line);
}
}
File.WriteAllLines(newLines, ...);
var linesInFile=File.ReadAllLines();
var newLines=新列表();
var toRandomize=新列表();
bool inRegion=false;
对于(int i=0;i
请参见将列表随机排列。我认为这样做很好
一次读取文件的所有文本
并使用正则表达式获取随机区域
并用其替换随机结果
以上步骤可以通过RegEx
类的Replace
方法完成
并最终将新内容保存到文件中
例如:
var regExp = @"(\[RAND\])(\w|\s|\d)*(\[/RAND\])";
var res = Regex.Replace(str, regExp, match =>
{
// suffle the and return result
// the return string replaced with occuring rand area
// for example with suffle algorithms
return "Randomized";
});
你到底想做什么?我不能很好地理解你的问题。我添加了另一个例子,使它更容易一些。基本上,它应该将.txt文件中
[RAND]
和[/RAND]
之间的行顺序打乱。非常感谢。没有意识到我可以这样读台词-非常有用!
var regExp = @"(\[RAND\])(\w|\s|\d)*(\[/RAND\])";
var res = Regex.Replace(str, regExp, match =>
{
// suffle the and return result
// the return string replaced with occuring rand area
// for example with suffle algorithms
return "Randomized";
});