[英]string.Replace() and string.Split() in c#
我有一堆存储在数组中的存储过程脚本。 每个数组都包含一个过程(即常规创建过程......)。 但是,当传递到数组时,文本中的空格将用数组中的\\ t和\\ r替换,而下一行将替换为\\ n。 现在,我想将每个过程文本分解为单词并存储在数组中。 但是分割功能
for (int i = 0; i < text.Length; i++)
{
string[] words = new string[text[i].Split('\t', '\n').Length];
}
上面的数组单词但是当我检查时,持有一个空值的字符串。 它不返回预期的单词。 我想可能是我必须在拆分之前替换\\ n \\ r \\ t,如下所示... \\
text[i].Replace("\n", string.Empty)
以上仍然无效。 请任何帮助将不胜感激。 我想将文本拆分为字符串。 下面是整个方法的快照。 该方法接收值的过程名称数组,我希望该方法提取每个给定名称的过程文本,然后将每个存储的过程文本拆分为多个词,以供以后使用。 我想遍历,通过确定后面紧跟哪个单词来执行简单的搜索。
更新
private void text(string[] array)
{
DataSet ds = new DataSet();
string sql = "";
progressBar1.Value = progressBar1.Minimum;
using (SqlCommand command = new SqlCommand())
{
string[] text = new string[array.Length];
string[] name = new string[array.Length];
for (int i = 0; i < array.Length; i++)
{
command.Parameters.Clear();
sql = @"SELECT DISTINCT so.name, so.type,text FROM sys.sysobjects so with (nolock) INNER JOIN sys.syscomments sc with (nolock)
ON so.id=sc.id WHERE name=@name";
command.Connection = getconnection();
command.CommandText = sql;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("@name", array[i].ToString());
using (SqlDataAdapter adp = new SqlDataAdapter(command))
{
ds = new DataSet();
adp.Fill(ds);
}
if (ds.Tables[0].Rows.Count > 0)
{
for (int j = 0; j < ds.Tables[0].Rows.Count; j++)
{
text[i] = ds.Tables[0].Rows[0]["text"].ToString();
name[i] = ds.Tables[0].Rows[0]["name"].ToString();
}
}
double e = (Convert.ToDouble(i) / Convert.ToDouble(array.Length));
progressBar1.Value = Convert.ToInt16(e * 100);
}
int count = 0 ;
for (int i = 0; i < text.Length; i++)
{
text[i].Replace("\n", string.Empty);
string[] words = new string[text[i].Split(new string[] { "\t", "\n" }, StringSplitOptions.RemoveEmptyEntries).Length];
for(int j = 0; j < words.Length ; j++)
{
// words[j] = text[i].Split(new string { " " }, StringSplitOptions.None);// = words[j].;
words[j] = words[j];
}
}
}
}
为了删除split语句中的空条目,请考虑以下重写...
string[] words = new string[text[i].Split(new string[] { "\t", "\n" }, StringSplitOptions.RemoveEmptyEntries ).Length];
祝好运!
您的字符串数组中充满了空字符串,因为您从未为其分配任何字符串。 您正在运行正确的Split
语句,对结果进行计数,然后将其丢弃而不将其保存在任何位置。
这行:
string[] words = new string[text[i].Split('\t', '\n').Length];
与这两个完全相同:
int length = text[i].Split('\t', '\n').Length;
string[] words = new string[length];
当您显式使用string[] s = new string[...]
创建数组时,您不是在为数组提供数据,而是在提供大小。 如果要将数据放入数组,则需要单独进行处理。
在这种情况下,使用new
是多余的string.Split
已经创建并填充了一个新数组并返回它,您可以将其分配给一个新变量,如下所示:
string[] words = text[i].Split('\t', '\n');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.