我在使用分隔符 &&
和 ||
拆分 C# 中的字符串时遇到问题。
例如字符串可能如下所示:
"(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)"
代码:
string[] value = arguments.Split(new string[] { "&&" }, StringSplitOptions.None);
我需要在没有 ()
大括号的情况下拆分或检索数组中的值 - 我需要输出为
"abc" "rfd" "5" "nn" "iu"
我需要它在一个数组中
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("a", "value1");
dict.Add("abc", "value2");
dict.Add("5", "value3");
dict.Add("rfd", "value4");
dict.Add("nn", "value5");
dict.Add("iu", "value6");
foreach (string s in strWithoutBrackets)
{
foreach (string n in dict.Keys)
{
if (s == n)
{
//if match then replace dictionary value with s
}
}
}
///Need output like this
string outputStr = "(value1)&&(value2)&&(value3)||(value4)&&(value5)||(value6)";
最佳答案
你应该试试这些:
string inputStr = "(abc)&&(rfd)&&(5)||(hh)&&(nn)||(iu)";
string[] strWithoutAndOR = inputStr.Split(new string[] { "&&","||" }, StringSplitOptions.RemoveEmptyEntries);
string[] strWithoutBrackets = inputStr.Split(new string[] { "&&","||","(",")" }, StringSplitOptions.RemoveEmptyEntries);
看看这个 working Example
As per MSDN docs: String.Split Returns a string array that contains the substrings in this instance that are delimited by elements of a specified string or Unicode character array. The split method is having few overloaded methods, you can make use of String.Split Method (String[], StringSplitOptions) for this scenario, where you can specify the subStrings that you want to refer for the split operation. The
StringSplitOptions.RemoveEmptyEntries
will helps you to remove empty entries from the split result
关于c# - 在 C# 中使用多个分隔符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47172159/