如何分割特殊字符'##'和& # 39;}& # 39;

本文关键字:分割 何分割 特殊字符 | 更新日期: 2023-09-27 17:51:04

我已经试过这里和这里了还是没有运气

Text1:

一些包含}和}或者}的文本

Text2:

一些包含##和##或者##的文本

Here My code

string str1 = "Some text that contained } and again } or maybe }";
// Some time its contained ##
string[] words;
if (str1.Contains("}"))
{
    words = str1.Split("}");
}
else if (str1.Contains ("##"))
{
    words = str1.Split("##");
} else {
    words = null;
}

I got 2 error

匹配'string '的最佳重载方法。Split(params char[])'有一些无效的参数

参数'1':不能从'string'转换为'char[]'}

如何分割特殊字符'##'和& # 39;}& # 39;

尝试使用

str1.Split(new [] {"}"}, StringSplitOptions.RemoveEmptyEntries);

str1.Split(new [] {"##"}, StringSplitOptions.RemoveEmptyEntries);
如果您想保留空字符串 ,则使用StringSplitOptions.None

字符串。Split只在下一个签名:Split(String[], StringSplitOptions)Split(String[], Int32, StringSplitOptions)中以字符串形式输入。所以至少您需要指定StringSplitOptions并将一个字符串转换为一个字符串的数组,否则编译器不知道您要调用什么方法。

您可以通过删除一条if语句来减少逻辑。如果没有发现输入字符串的出现,Split方法不会抛出任何异常。

string str1 = "Some text that contained } and again } or maybe }";
string[] words;
if (str1.Contains("}") || str1.Contains ("##"))
{
    words = str1.Split(new [] {"}", "##"}, StringSplitOptions.RemoveEmptyEntries);
}
else
{
    words = null;
}
str1.Split(new [] {"}","##"}, StringSplitOptions.RemoveEmptyEntries);

正如Dave提到的,字符串分割只接受一个字符。如果需要对字符串进行分割,请使用以下代码

string str1 = "Some text that contained } and again } or maybe }";
    // Some time its contained ##
string[] words;
if (str1.Contains("}"))
{
    words = str1.Split(new string[] { "}" }, StringSplitOptions.None);
}
else if (str1.Contains ("##"))
{
    words = str1.Split(new string[] { "##" }, StringSplitOptions.None);
} else {
    words = null;
}

如果您需要匹配"##",您可以将字符串数组传递给string.split

tring[] separators = {"##"};
string [] sarr = mystr.Split(separators);

试试下面的代码。注意,您也可以使用Regex,所以这个类将允许您按模式进行分割:

string str1 = "Some text that contained } and again } or maybe }";
// Some time its contained ##
string[] words;
if (str1.Contains("}"))
{
    words = str1.Split('}');
}
else if (str1.Contains ("##"))
{
    words = Regex.Split(str1, @"'#'#");
} else {
    words = null;
}

在c#中string. split()的工作方式,你传入的参数应该是一个字符数组或带选项的字符串。该方法还有其他重载,但这些与您的问题无关。
代替words = str1.Split("}"),你应该使用words = str1.Split('}'),它传递一个字符,而不是一个字符串作为参数。
对于需要检查字符串而不是字符的情况,应该使用words = str1.Split(new string[] { "##" }, StringSplitOptions.None)而不是words = str1.Split("##")

你的最终代码应该看起来像
string str1 = "Some text that contained } and again } or maybe }";
        // Some time its contained ##
string[] words;
if (str1.Contains("}"))
{
    words = str1.Split( ('}'));
}
else if (str1.Contains("##"))
{
    words = str1.Split(new string[] { "##" }, StringSplitOptions.None);
}
else
{
    words = null;
}

点击这里查看如何使用分割方法的教程

如果你想用}或##分割两个字符串,你可以使用你想分割的字符串数组。

stringToSplit.Split(new []{"}","##"}, StringSplitOptions.None);

看看这个工作,看看这个涂鸦如何使用字符串的例子。正确地分割

为什么不在一行中完成呢

str1 = "Some text that contained } and again } or maybe }"; 
var items = str1.Split(new string[] { "##" ,"}" },StringSplitOptions.RemoveEmptyEntries);