0

I have code that finds largest word that starts with a capital letter. But I need that word to add a separator and space. Any ideas how I should do it properly?

char[] skyrikliai = { ' ', '.', ',', '!', '?', ':', ';', '(', ')', '\t' };
string eilute = "Arvydas (g. 1964 m. gruodzio 19 d. Kaune)– Lietuvos, krepsininkas, olimpinis ir pasaulio cempionas, nuo 2011 m. spalio 24 d.";

static string Ilgiausias(string eilute, char[] skyrikliai)
{
        string[] parts = eilute.Split(skyrikliai,
        StringSplitOptions.RemoveEmptyEntries);
        string ilgiaus = "";

        foreach (string zodis in parts)
            if ((zodis.Length > ilgiaus.Length) && (zodis[0].ToString() == zodis[0].ToString().ToUpper()))
                ilgiaus = zodis;
        return ilgiaus;
    }

It should find word Lietuvos and add , and space

Result should be "Lietuvos, "

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

3

I would use LINQ for that:

var ilgiaus = parts.Where(s => s[0].IsUpper())
                   .OrderByDescending(s => s.Length)
                   .FirstOrDefault();

if(ilgiaus != null) {
   return ilgiaus + ", ";
}
Lukas Kabrt
  • 5,441
  • 4
  • 43
  • 58
1

Also you can use regex and linq. You dont need to split by many characters.

Regex regex = new Regex(@"[A-Z]\w*");
string str = "Arvydas (g. 1964 m. gruodzio 19 d. Kaune)– Lietuvos, krepsininkas, olimpinis ir pasaulio cempionas, nuo 2011 m. spalio 24 d.";

string longest = regex.Matches(str).Cast<Match>().Select(match => match.Value).MaxBy(val => val.Length);

if you dont want to use MoreLinq, instead of MaxBy(val => val.Length) you can do OrderByDescending(x => x.Length).First()

M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
0

There are probably more ingenious and elegant ways, but the following pseudocode should work:

List<String> listOfStrings = new List<String>();
// add some strings to the generic list
listOfStrings.Add("bla");
listOfStrings.Add("foo");
listOfStrings.Add("bar");
listOfStrings.Add("Rompecabeza");
listOfStrings.Add("Rumpelstiltskin");
. . .
String longestWorld = String.Empty;
. . .
longestWord = GetLongestCapitalizedWord(listOfStrings);
. . .

private String GetLongestCapitalizedWord(List<String> listOfStrings)
{
    foreach (string s in listofstrings)
    {
      if ((IsCapitalized(s) && (s.Len > longestWord.Len)))
      {
          longestWord = s;
      } 
    }
}

private bool IsCapitalized(String s)
{
    return // true or false
}
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862