[英]String extraction in C#
I'm getting pretty frustrated with this, and hope the community can help me out. 我对此感到非常沮丧,并希望社区可以帮助我。
I have a string, an example would be "1_ks_Males", another example would be "12_ks_Females". 我有一个字符串,一个例子是“1_ks_Males”,另一个例子是“12_ks_Females”。
What I need to do is write a method that extract's each value. 我需要做的是编写一个提取每个值的方法。 So from the first example I'd want something like this: 所以从第一个例子我想要这样的东西:
1 ks Males 1 ks男性
In separate variables. 在单独的变量中。
I'm sure I'm just being incredibly thick, but I just can't get it! 我敢肯定我只是非常厚实,但我无法得到它!
Simply use string.Split('_')
. 只需使用string.Split('_')
。 With your input strings it will return a string
array with three elements. 使用输入字符串,它将返回一个包含三个元素的string
数组。
You can use Split
function for String
. 您可以对String
使用Split
函数。 Something like this 像这样的东西
var split = "1_ks_Males".Split('_');
var first = split[0];
var second = split[1];
var third = split[2];
string[] array = "1_ks_Males".Split('_');
Assert.AreEqual("1",array[0])
Assert.AreEqual("ks",array[1])
Assert.AreEqual("Males",array[2])
var values = "1_ks_Males".Split('_');
// values[0]: 1
// values[1]: ks
// values[2]: Males
How about this? 这个怎么样?
var data = myString.Split("_");
var value = data[0];
var @type = data[1];
var gender = data[2];
use String.Split
which returns an array of values 使用String.Split
返回值数组
var values = "12_ks_Females".split("_");
// values[0] == "12"
// values[1] == "ks"
// values[2] == "Females"
You could use split
- 你可以使用split
-
var s = "1_ks_Males";
string[] values = s.Split('_');
Your values will then be contained in the `values' array - 您的值将包含在`values'数组中 -
var firstvalue = values[0];
var secondvalue = values[1];
var thirdvalue = values[2];
You'll want to look into the String.Split
method of the String class. 您将要查看String类的String.Split
方法。 Here's the MSDN link . 这是MSDN链接 。
Basically, if all of your strings have the values that you require separated by a consistent character (in your example, this is an underscore character), you can use the Split
method which will split a single string into an array of new strings based upon a specific separator. 基本上,如果所有字符串都具有由一致字符分隔的值(在您的示例中,这是一个下划线字符),您可以使用Split
方法,该方法将单个字符串拆分为基于的新字符串数组特定的分隔符。
For example: 例如:
string s = "1_ks_Males";
string[] v = s.Split('_');
Console.WriteLine(v[0]);
Console.WriteLine(v[1]);
Console.WriteLine(v[2]);
would output: 输出:
1
ks
Males
You should use the String.Split method. 您应该使用String.Split方法。
Like: string[] splitParts = "1_ks_Males".Split('_');
喜欢: string[] splitParts = "1_ks_Males".Split('_');
这应该做的伎俩:
var values = myString.Split('_');
var splitVar = "1_ks_Males".Split('_');
var firstVar = splitVar[0];
var secondVar = splitVar[1];
var thirdVar = splitVar[2];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.