If the function deals with strings then the second parameter should be removed.
The function should return a pointer to the first upper case letter or a null pointer if such a letter is not present in the string. That is the function declaration and behavior should be similar to the declaration and behavior of the standard string function strchr
. The only difference is that your function does not require a second parameter of the type char
because the searched character is implicitly defined by the condition to be an upper case character.
On the other hand, though your function has the return type char it returns an integer that specifies the position of the found character. Also your function does not make a difference between the situations when an upper case character is not found and when a string contains an upper case character in its first position.
Also your function has too many if-else statements.
The function can be declared and defined the following way as it is shown in the demonstrative program below.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char * first_capital( const char s[] )
{
const char *first = s;
const char *last = s + strlen( s );
while ( first < last )
{
const char *middle = first + ( last - first ) / 2;
if ( islower( ( unsigned char )*middle ) )
{
first = middle + 1;
}
else
{
last = middle;
}
}
return ( char * )( isupper( ( unsigned char )*first ) ? first : NULL );
}
int main(void)
{
const char *s = "";
char *result = first_capital( s );
if ( result )
{
printf( "%c at %zu\n", *result, ( size_t )( result - s ) );
}
else
{
printf( "The string \"%s\" does not contain an upper case letter.\n", s );
}
s = "a";
result = first_capital( s );
if ( result )
{
printf( "%c at %zu\n", *result, ( size_t )( result - s ) );
}
else
{
printf( "The string \"%s\" does not contain an upper case letter.\n", s );
}
s = "A";
result = first_capital( s );
if ( result )
{
printf( "%c at %zu\n", *result, ( size_t )( result - s ) );
}
else
{
printf( "The string \"%s\" does not contain an upper case letter.\n", s );
}
s = "abcdefA";
result = first_capital( s );
if ( result )
{
printf( "%c at %zu\n", *result, ( size_t )( result - s ) );
}
else
{
printf( "The string \"%s\" does not contain an upper case letter.\n", s );
}
s = "abAB";
result = first_capital( s );
if ( result )
{
printf( "%c at %zu\n", *result, ( size_t )( result - s ) );
}
else
{
printf( "The string \"%s\" does not contain an upper case letter.\n", s );
}
return 0;
}
The program output is
The string "" does not contain an upper case letter.
The string "a" does not contain an upper case letter.
A at 0
A at 6
A at 2