您包括了退货声明
return -1;
在while循环中
while(n>=0)
{
if(str[n]==t)
{
return n;
}
else
{
n=n-1;
}
return -1;
}
将其放在循环之外。
请注意该函数应声明为
size_t strrindex( const char str[], char t );
并在由于标准 C 函数的( size_t )-1
返回类型为 而找不到字符的情况下返回。strlen
size_t
请记住,有一个类似的标准 C 函数
char *strrchr(const char *s, int c);
这是一个演示程序
#include <stdio.h>
#include <string.h>
size_t strrindex( const char *s, char c )
{
size_t n = strlen( s );
while ( s[n] != c && n != 0 ) --n;
return n == 9 ? -1 : n;
}
int main(void)
{
const char *s = "Hello";
size_t n = strlen( s );
do
{
size_t pos = strrindex( s, s[n] );
if ( pos == -1 )
{
printf( "The character %c is not found\n", s[n] );
}
else
{
printf( "The character %c is found at position %zu\n", s[n] == '\0' ? '0' : s[n], pos );
}
} while ( n-- );
return 0;
}
它的输出是
The character 0 is found at position 5
The character o is found at position 4
The character l is found at position 3
The character l is found at position 3
The character e is found at position 1
The character H is found at position 0
如果要从搜索中排除终止零,则该函数可以如下所示
#include <stdio.h>
#include <string.h>
size_t strrindex( const char *s, char c )
{
size_t n = strlen( s );
while ( n != 0 && s[n - 1] != c ) --n;
return n == 0 ? -1 : n - 1;
}
int main(void)
{
const char *s = "Hello";
size_t n = strlen( s );
do
{
size_t pos = strrindex( s, s[n] );
if ( pos == -1 )
{
printf( "The character %c is not found\n", s[n] == '\0' ? '0' : s[n] );
}
else
{
printf( "The character %c is found at position %zu\n", s[n] == '\0' ? '0' : s[n], pos );
}
} while ( n-- );
return 0;
}
在这种情况下,程序输出是
The character 0 is not found
The character o is found at position 4
The character l is found at position 3
The character l is found at position 3
The character e is found at position 1
The character H is found at position 0
还要注意该函数scanf
读取一个字符串,直到遇到一个空白字符。
所以而不是scanf
使用fgets
. 例如
fgets( str, sizeof( str ), stdin );
str[strcspn( str, "\n" )] = '\0';