我有一个[]string retry
我内心有一些字符串让我们说:
a 2,a 3,h 9,asd 123等。它们都有字母和整数之间的间隔。现在我需要知道字母部分有多长(在这种情况下,“qwe 2”字母长度为3,整数部分为2)。我稍后使用指定索引处的.substring,字母部分结束,整数开始。
string[] s = new string[5];
List<string> retry = new List<string>();
int max = 1;
for (int i = 0; i < s.Length; i++)
{
s[i] = Console.ReadLine();
}
Console.WriteLine(" ");
Array.Sort(s);
for (int j = 0; j < s.Length; j++)
{
if (j > 0)
{
if (s[j] == s[j - 1])
{
max++;
if (retry.Any(x => x.Contains(s[j])))
{
retry.Add(s[j] + " " + max);
}
else
{
if (j <= s.Length - 1)
{
if (s[j-1] != s[j])
{
retry.Add(s[j] + " " + max);
}
else
{
retry.Add(s[j] + " " + max);
}
}
}
}
else
{
max = 1;
}
}
}
for (int j = 0; j < retry.ToArray().Length; j++)
{
for (int k = j + 1; k < retry.ToArray().Length; k++)
{
var a1=retry[j].Substring(0,1);
var a2 = retry[k].Substring(0,1);
if(a1==a2)
{
var b1 = retry[j].Substring(2);
var b2 = retry[k].Substring(2);
if(int.Parse(b1)>int.Parse(b2))
{
retry.Remove(a2 + " "+ b2);
}
else
{
retry.Remove(a1 + " " + b1);
}
}
}
Console.WriteLine(retry[j]);
}
Console.ReadKey();
这仅适用于1个字母。
答案 0 :(得分:2)
下面的代码应该按预期得到结果:
string [] entries = {"xyz 1","q 2","poiuy 4"};
for(int i=0;i<entries.Length;i++)
{
var parts = entries[i].Split(' ');
var txtCount = parts[0].Length;
Console.WriteLine(String.Format("{0} {1}", txtCount, parts[1]));
}
答案 1 :(得分:1)
怎么样......
string[] test = new [] { "qwe 2", "a 2", "b 3", "asd 123" };
foreach (var s in test)
{
var lastLetterIndex = Array.FindLastIndex(s.ToCharArray(), Char.IsLetter);
var lastNumberIndex = Array.FindLastIndex(s.ToCharArray(), Char.IsNumber);
Console.WriteLine(s);
Console.WriteLine("Letter Length : " + (lastLetterIndex + 1));
Console.WriteLine("Number Length : " + (lastNumberIndex - lastLetterIndex));
}
Console.ReadKey();
答案 2 :(得分:0)
这将迭代所有字符串并计算字符的长度,并存储数字的值及其索引。请注意,每次迭代都会丢失此信息,但如果您需要的信息的持续时间超过迭代的持续时间,我会留下您的担心。
int letterLength = 0, number = 0, index = 0;
string[] testString = { "a 2", "a 3", "h 9", "asd 123", "sw", "swa23", "swag 2464" };
foreach (string str in testString)
{
letterLength = 0;
index = -1;
int i = 0;
for (; i < str.Length; i++)
{
char c = str[i];
if (Char.IsLetter(c)) letterLength++;
else if (Char.IsNumber(c)) break;
}
StringBuilder strBuilder = new StringBuilder();
for (; i < str.Length; i++)
{
char c = str[i];
if (index == -1) index = str.IndexOf(c);
strBuilder.Append(c);
number = Int32.Parse(strBuilder.ToString());
}
Console.WriteLine($"String: {str}\nLetter Length: {letterLength} Number: {number} Index: {index}\n");
}