-2

string myStr = "part1#part2";

要拆分这个简单的字符串 Split() 方法,需要传递带有参数的数组。真的吗?为什么我不能只指定myStr.Split('#');如果我不需要他们为什么希望我声明 char 数组。任何人都可以解释我的逻辑或我的误解吗?谢谢

4

2 回答 2

8

你可以。String.Split接受一个param参数,它允许可变数量的参数。

以下按预期工作

var text = "a,a,a";
var parts = text.Split(',');
于 2013-03-30T01:09:17.357 回答
0

其他方式,


更多关于棕狐的信息

string data = "THE1QUICK1BROWN1FOX";

return data.Split(new string[] { "1" }, StringSplitOptions.None);

更多来自http://stackoverflow.com

var str = "google.com 420 AM 3 May 12";
var domain = str.Split(' ')[0];           // google.com
var tld = domain.Substring(domain.IndexOf('.')) // .com

参考:http: //msdn.microsoft.com/en-us/library/b873y76a.aspx

我迟到了,但是,

一个简单的导师


Split() 方法的最简单语法接受一个字符数组作为它的唯一参数,列出用于确定字符串拆分位置的字符。它返回一个字符串数组,数组的每个元素对应于指定分隔符之间的值。下面的行来自清单中的第一个拆分操作:

    string[] year = commaDelimited.Split(new char[] {','});

以类似的方式,可以使用 Join() 方法将数组的元素组合成定界字符串。Join() 方法的最简单重载接受两个参数:一个字符串,用于分隔每个数组元素,以及要组合的元素数组。Join() 方法是静态的,需要 String 类型标识符而不是字符串实例来实现命令。清单中的以下行创建了一个字符串,其中包含按顺序的所有年份元素,用冒号分隔:

    string colonDelimeted = String.Join(":", year);

重载


这些是这些方法的简单实现,可能是最有可能使用的。现在让我们看一下它们的几个重载,看看如何实现更专业的行为。

Split() 方法有一个带有第二个参数的重载,指定要实现的分隔数。下一行将 commaDelimited 字符串分成三个数组元素:

    string[] quarter = commaDelimited.Split(new Char[] {','}, 3);

乍一看,可能会认为这三个数组元素可能是 Jan、Feb 和 Mar,但事实并非如此。第一个数组元素是 Jan,第二个是 Feb,最后一个是字符串的其余部分。为了自己看,这里是每个数组元素用空格分隔的输出字符串:

Jan Feb Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

The Join() method has an overload that allows you to extract a subset of an array. The first two parameters are the same as previously described, and the third and fourth parameters specify the position in the array to begin reading and the number of elements to read, respectively. The following line from the listing creates a string with a forward slash between the sixth through eighth elements of the year array:

    string thirdQuarter = String.Join("/", year, 6, 3);
于 2013-03-30T01:48:23.263 回答