[英]Parse through an array of strings to check how many times there's a value
Say I have this array of strings: 假设我有以下字符串数组:
string[] arrayToParse = {2, G, R, G, B};
I need to parse through the array to check how many times is a string present so that I may end up with values like this: 我需要解析整个数组以检查一个字符串存在多少次,以便最终得到这样的值:
2
GG
R
B
So each time the loop detects if there's another string identical, he "concatenates", then add the value to a list. 因此,每次循环检测到是否还有另一个相同的字符串时,他都会“连接”,然后将值添加到列表中。
If I take another example: string[] arrayToParse2 = {2, Q, T, T, U, U}
Should end up with these values: 如果再举一个例子:
string[] arrayToParse2 = {2, Q, T, T, U, U}
应该以这些值结尾:
2
Q
TT
UU
Any help anyone? 任何人有帮助吗?
Use LINQ ( GroupBy
method) and string.Join
: 使用LINQ(
GroupBy
方法)和string.Join
:
string[] arrayToParse = {"2", "G", "R", "G", "B"};
string[] results = arrayToParse.GroupBy(x => x)
.Select(g => string.Join(string.Empty, g))
.ToArray();
Works for both your sample inputs. 适用于两个示例输入。
You can use Linq: 您可以使用Linq:
var stringGroups = arrayToParse.GroupBy(str => str);
Now you can display these groups with String.Join
: 现在,您可以使用
String.Join
显示这些组:
foreach(var group in stringGroups)
Console.WriteLine(string.Join("", group));
I would go with the LINQ approach. 我会使用LINQ方法。 If it is not available or you don't want to use it, here is a longuer version (easier to understand if you've never used LINQ).
如果它不可用或者您不想使用它,则可以使用更长的版本(如果您从未使用过LINQ,则更容易理解)。
string[] arrayToParse = {2, G, R, G, B};
List<String> parsedList = new List<String>
foreach(String sToParse in arrayToParse)
{
if (parsedList.Count <= 0)
parsedList.Add(sToParse);
else
foreach(String sInParsedList in parsedList)
{
if(sToParse == sInParsedList)
sInParsedList += sToParse;
else
parsedList.Add(sToParse);
}
string[] parsedArray = parsedList.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.