找到没有任何数字的最长子字符串和至少一个大写字符C#

时间:2017-05-07 12:14:14

标签: c# data-structures

我必须使用c#找到没有任何数字的最长SubString和至少一个大写字符。如果字符串是“sdcF01h”那么o / p应该是“sdcF” 我的方法。

String testString = "sdcF01F";
//var splitString = testString.Split("[0-9]");
int startIndex = 0;
int longestStartIndex = 0;
int endIndex = 0;
int index = 0;
int longestLength = int.MinValue;
bool foundUpperCase = false;
while (index <= testString.Length)
{
    if (index == testString.Length || char.IsDigit(testString[index]))
    {
        if (foundUpperCase && index > startIndex && index - startIndex > longestLength)
        {
            longestLength = index - startIndex;
            endIndex = index;
            longestStartIndex = startIndex;
        }
        startIndex = index + 1;
        foundUpperCase = false;
    }
    else if (char.IsUpper(testString[index]))
    {
        foundUpperCase = true;
    }
    index++;
}
endIndex--;
var res1 = testString.Substring(longestStartIndex, endIndex);
Console.WriteLine(res1);

但这不是最佳解决方案。

2 个答案:

答案 0 :(得分:0)

只需拆分,按长度排序,然后测试上层

public static string GetSubset(string input = "LKAH8slfsfjlllj9lkjlkjasdf;lk7ljasdflkasdjsfdljk")
{
    if (string.IsNullOrEmpty(input))
        return string.Empty;
    foreach(String s in input.Split(new Char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }).OrderByDescending(x => x.Length))
    {
        foreach (char c in s)
            if (char.IsUpper(c))
                return s;
    }
    return string.Empty;
}

答案 1 :(得分:-1)

   var abc= Regex.Matches("co12dEname123abP", @"[a-zA-Z]+|\d+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
    List<string> lst = new List<string>();

    for (int i = 0; i < abc.Length; i++)
    {
        if (abc[i].Any(char.IsDigit))
            continue;
        if (abc[i].Any(c => char.IsUpper(c)))
            lst.Add(abc[i]);
    }
    var finalOutput =lst.OrderByDescending(x => x.Length).FirstOrDefault();