i am trying to learn c sharp and started playing with lists today and would like to know if i am headed in the right direction here or if i should look into making an Array or something else here is some sample code: now what i want to do is find the string with the largest/longest characters in it looking at the code it would be 'jessie' because there are 6 chars in that name. of course the program i am playing with has thousands of names. so i can just throw the log.Add(string) into a foreach loop that is simple enough but how i would i determine which string in that list is the longest, i dont really care about white space or non letters, just the char count. thanks in advance. O and i did search for this for about two hours before posting and it seems alot of people put there homework on here for help to get an A. i am not in school just trying to teach myself the language and would greatly appreciate any feed back. thanks
static List<string> log = new List<string>();
string a = "John", b = "Sally", c = "jessie";
log.Add(a);
log.Add(b);
log.Add(c);
foreach(string L in log)
{
Console.WriteLine(L);
}
//here i would like Console.WriteLine("{0} is the longest name.", /*longest char count in the list here*/);
|
|
theLizardPosted Jul 26, 2010, 12:10 AM
string longest=""
int longestindex =-1;
for(int i = 0; i < log.Length; i++)
{
if(L .Length > longest.Length)
{
longest = L;
longestindex = i;
}
}
at the end of this you should have the index to the longest string,
Console.WriteLine(log[longestindex]);
or
Console.WriteLine(longest);
or if you don't want the index
foreach(string L in log)
{
if(L .Length > longest.Length)
{
longest = L;
}
}
ChrisPosted Oct 16, 2015, 2:34 PM
André SkyttePosted Oct 8, 2015, 6:09 AM
ChrisPosted Jul 26, 2010, 1:34 AM
string longest = "";
foreach(string L in log)
{
if (L.Length > longest.Length)
{
longest = L;
}
} Console.Write(longest);