[英]Is it possible to convert an array of strings into one string?
在我的程序中,我使用以下语句读入文件:
string[] allLines = File.ReadAllLines(dataFile);
但我想将一个正则表达式作为一个整体应用于该文件(示例文件显示在底部)所以我可以消除我在文件中不关心的某些东西。 我不能使用ReadAllText,因为我需要逐行读取它以用于程序的另一个目的(从每行中删除空格)。
Regex r = new Regex(@"CREATE TABLE [^\(]+\((.*)\) ON");
(感谢chiccodoro获取此代码)
这是我想申请的正则表达式。
有没有办法将数组更改回一个文本文件? 或者问题的任何其他解决方案?
我想到的东西就是用string.Empty
替换我不关心的'东西'。
示例文件
USE [Shelleys Other Database]
CREATE TABLE db.exmpcustomers(
f_name varchar(100) NULL,
l_name varchar(100) NULL,
date_of_birth date NULL,
house_number int NULL,
street_name varchar(100) NULL
) ON [PRIMARY]
您可以将string []连接到这样的单个字符串中
string strmessage=string.join(",",allLines);
输出: - 一个单独的字符串。
您可以使用String.Join()
:
string joined = String.Join(Environment.NewLine, allLines);
如果您只想将其写回文件,则可以使用File.WriteAllLines()
并使用数组。
String.Join
将使用任何指定的分隔符连接数组的所有成员。
使用regexen一次处理多行数据真的很难。 因此,我建议您首先将其作为一个大字符串读取,执行您的多行正则表达式业务,然后使用String.Split将其拆分为字符串数组(拆分为新行)。 您希望按此顺序执行此操作的原因是,对文件数据的任何进一步操作都将包括正则表达式已经进行的更改。 如果您加入字符串,然后执行正则表达式,您将需要再次拆分该字符串,或者在操作原始数组时丢失对其进行的更改。
请记住将其用于正则表达式匹配,以便它与新行匹配:
Regex r = new Regex(@"CREATE TABLE [^(]+((.*)) ON", RegexOptions.SingleLine);
只是改变
string[] allLines = File.ReadAllLines(dataFile);
至
string allLines = File.ReadAllText(dataFile);
;)
public string CreateStringFromArray(string[] allLines)
{
StringBuilder builder = new StringBuilder();
foreach (string item in allLines)
{
builder.Append(item);
//Appending Linebreaks
builder.Append("\n\l");
}
return builder.ToString();
}
你在每一行读到的时候可以建立一个缓冲区吗? 我认为这可能比将所有行作为字符串数组,然后加入它们更有效(...虽然我没有对该问题进行全面研究,并且有兴趣听听是否存在某种原因,这样做实际上更有效率)。
StringBuilder buffer = new StringBuilder();
string line = null;
using (StreamReader sr = new StreamReader(dataFile))
{
while((line = sr.ReadLine()) != null)
{
// Do whatever you need to do with the individual line...
// ...then append the line to your buffer.
buffer.Append(line);
}
}
// Now, you can do whatever you need to do with the contents of
// the buffer.
string wholeText = buffer.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.