c# - 在 C# 中使用多个分隔符拆分字符串

标签 c#

我在使用分隔符 &&|| 拆分 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/

相关文章:

c# - 是否可以禁用 C# 中的函数

c# - 如何在 mvc c# 中解密 FormsAuthenticationTicket?

c# - Azure DocumentDB,使用 LINQ 在字典中搜索

c# - 如何使用 LINQ 获取数组重叠?

c# - 如何获取 Combobox.Datasource 到字典?

c# - Python 等同于 C# 的 .Select?

c# - 使用 log4net 连接字符串

c# - 通过脚本找对撞机

c# - 无法使用 GetManifestResourceStream 找到嵌入式资源

c# - Visual C# 中的 _stat 替代项