I have an array that has a list of 15 different country names. I have to create a function that finds the largest name and returns its index, and if there are more then one that have a maximum length equivalent to each other it only has to return 1 of the indexes to the names. (Example below).
I'll admit and say I'm quite new to c. But have tried using the strlen(), and the strcmp() functions. I know I'm probably missing something huge here, but any help would be better then where I'm at now. Thanks in advance!
Here's what I thought would work:
int maxCountry(char countryNames[15][50]){
int i, x = 0, length, length2, returnVal;
char string[50], string2[50];
for(i = 0; i < 15; i ){
string = countryNames[i] ;
length = strlen(string);
string2 = countryNames[x];
length2 = strlen(string2);
if(length < length2){
returnVal = x;
x = i;
}
}
return returnVal;
}
CodePudding user response:
I had trouble following your code's logic, I think it does a few operations that are not needed.
Here's my attempt at it, with the following obvious changes:
- Treat the array as an array of strings, not a 2d array.
- Pass in the number of strings.
- Return the index of the longest string, or -1 on error.
#include <stdio.h>
#include <string.h>
int longest(const char **s, size_t n)
{
size_t maxlen = 0;
int maxpos = -1;
for (size_t i = 0; i < n; i)
{
const size_t len = strlen(s[i]);
if (len > maxlen)
{
maxlen = len;
maxpos = (int) i;
}
}
return maxpos;
}
int main(void)
{
const char *s[] = { "foo", "hello", "you", "monster", "test" };
printf("The longest is at %d\n", longest(s, sizeof s / sizeof *s));
return 0;
}
This prints:
The longest is at 3
CodePudding user response:
You don't need 2 variables, and you want to compare against a stored length (initialized to 0)
int maxCountry(char (*countryNames)[50], size_t countries)
{
size_t max_length = 0;
int result = 0;
for(size_t i = 0; i < countries; i )
{
size_t length = strlen(countryNames[i]);
if (length > max_length)
{
max_length = length;
result = i;
}
}
return result;
}