关于拆分字符串的帮助 - c# [英] Help regarding splitting string - c#
问题描述
大家好,
我希望有人可以帮我解决这个问题。
我有一个字符串列表,如下所示:
hello everyone,
I hope someone can help me with this issue.
I have a list of strings as shown below:
12|string|string2|username_one|string3|somenumbers123456789012
123|string1|string2|username_two|string3|somenumbers34566789901234
1245|string1|string2|username_three|string3|somenumbers123456788900
我需要的是从字符串中提取用户名,而不是|
字符
请注意,所有字符串和用户名的长度都不同。
提前谢谢!
问候,
Aleksandar
What I need is to extract username from string, without "|"
characters
Note that all strings and usernames are different lengths.
Thank you in advance!
Regards,
Aleksandar
推荐答案
string[] data = yourstring.Split('|');
data [3]
将包含您的用户名:)
更新:Be因为我看到其他人试图完全解决...
用这个来开始提取数据:
data[3]
will contain your username :)
Update: Because I saw some others try to solve fully...
Use this to extract data initially:
string[] data = File.ReadAllLines("file were converting to string");
string[] usernames = new string[# of usernames];
for (i = 0; i < data.Count(); i++)
{
string[] username = data[i].Split('|')[3];
}
你可以使用Linq:
You can use Linq:
List<string> myList = new List<string>(){@"12|string|string2|username_one|string3|somenumbers123456789012",
@"123|string1|string2|username_two|string3|somenumbers34566789901234",
@"1245|string1|string2|username_three|string3|somenumbers123456788900"};
//var qry = myList.Select(a=>Tuple.Create(a.Split('|')[0], a.Split('|')[1], a.Split('|')[2], a.Split('|')[3], a.Split('|')[4], a.Split('|')[5]));
var qry = myList.Select(a=>a.Split('|')).Select(a=>Tuple.Create(a[0], a[1], a[2], a[3], a[4], a[5]));
//for direct casting
//var qry = myList.Select(a=>a.Split('|')).Select(a=>new Tuple<string, string, string, string, string, string>(a[0], a[1], a[2], a[3], a[4], a[5]));
foreach(var row in qry)
{
Console.WriteLine("{0} {1} {2} {3} {4} {5}", row.Item1, row.Item2, row.Item3, row.Item4, row.Item5, row.Item6 );
}
结果:
Result:
12 string string2 username_one string3 somenumbers123456789012
123 string1 string2 username_two string3 somenumbers34566789901234
1245 string1 string2 username_three string3 somenumbers123456788900
所以,如果你愿意的话如果只获取用户名,请使用:
So, if you would like to get only user names, use:
var qry = myList.Select(a=>a.Split('|')[3]);
你可以看到字符串的长度是无关紧要的......每个字符串具有相同数量的部分是相关的,由管道标志(|)分隔......
你需要做的就是把每一行分成它的部分...
You can see that the length of the strings is irrelevant...What is relevant that every string has the same number of parts, separated by the pipe sign (|)...
What you have to do is take every line and split it to its parts...
string [] array = line.Split(new Char [] {'|'});
现在这个字符串数组created具有完全相同的元素数,在第3个位置你有用户名...
Now that array of string created has the exact same number of element and at the 3rd position you have the user-name...
string user_name = array[3];
这篇关于关于拆分字符串的帮助 - c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!