Dev*_*osh 6 .net c# regex string
我正在使用c#.net开发一个应用程序,其中我需要如果用户输入的输入包含字符' - '(连字符),那么我想连接连字符( - )的直接邻居,例如,如果用户输入
A-B-C then i want it to be replaced with ABC
AB-CD then i want it to be replaced like BC
ABC-D-E then i want it to be replaced like CDE
AB-CD-K then i want it to be replaced like BC and DK both separated by keyword and
Run Code Online (Sandbox Code Playgroud)
得到这个后,我必须准备我的查询到数据库.
我希望我能解决问题,但如果需要更多澄清,请告诉我.任何帮助将不胜感激.
谢谢,Devjosh
未经测试,但这应该可以解决问题,或者至少引导您走向正确的方向。
private string Prepare(string input)
{
StringBuilder output = new StringBuilder();
char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (chars[i] == '-')
{
if (i > 0)
{
output.Append(chars[i - 1]);
}
if (++i < chars.Length)
{
output.Append(chars[i])
}
else
{
break;
}
}
}
return output.ToString();
}
Run Code Online (Sandbox Code Playgroud)
如果您希望每一对在数组中形成一个单独的对象,请尝试以下代码:
private string[] Prepare(string input)
{
List<string> output = new List<string>();
char[] chars = input.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
if (chars[i] == '-')
{
string o = string.Empty;
if (i > 0)
{
o += chars[i - 1];
}
if (++i < chars.Length)
{
o += chars[i]
}
output.Add(o);
}
}
return output.ToArray();
}
Run Code Online (Sandbox Code Playgroud)