替换c#字符串中的逗号
本文关键字:字符串 替换 | 更新日期: 2023-09-27 18:10:54
我有一个这样的字符串:
select name,lastname,email from contacts
我想替换+"|"+的逗号然后得到像这样的
select name+"|"+lastname+"|"+email from contacts
. replace这容易 (",",+"|"+);
但是问题是当我面对这样的字符串时:
select name,lastname,isnull(email,0) from contacts
如何检测以避免isnull()内的逗号?通过替换,我得到了这样的字符串
select name+"|"+lastname+"|"+isnull(email+"|"+0) from contacts
这是错误的!
谢谢。
试试这个:
public static string ReplaceTopLevelCommas(string query)
{
var newQuery = new StringBuilder();
var level = 0;
foreach (var c in query)
{
if (c == ',')
{
if (level == 0)
{
newQuery.Append("+'"|'"+");
}
else
{
newQuery.Append(c);
}
}
else
{
if (c == '(')
{
level++;
}
else if (c == ')')
{
level--;
}
newQuery.Append(c);
}
}
return newQuery.ToString();
}
仅当逗号不在任何圆括号内时才替换它们。所以它也适用于多级嵌套。
工作示例:http://ideone.com/TGPRe2
只需编写自己的方法:
private static string replace_commas(String str_)
{
StringBuilder str = new System.Text.StringBuilder(str_);
bool replace = true;
for(int i = 0; i != str.Length; ++i)
{
if(str[i] == ',' && replace)
str[i] = '|';
if(str[i] == '(')
{
replace = false;
continue;
}
if(str[i] == ')' && !replace)
replace = true;
}
return str.ToString();
}
你来填空!: -)