返回字符t在字符串s中最右边出现的位置,若s中不包括t,则返回-1


#include
//返回字符t在字符串s中最右边出现的位置,若s中不包括t,则返回-1
int strrindex( char s[], char t )
{
  int i;
  int count = -1;
 
  for(i=0; s[i] != '\0'; i++)
  {
    if(s[i] == t)
    {
      count = i;
    }
  }
 
  return count;
}
 
typedef struct TEST
{
  char *data;
  char testchar;
  int expected;
} TEST;
 
int main(void)
{
  TEST test[] =
  {
    {"Hello world", 'o', 7},
    {"This string is littered with iiiis", 'i', 32},
    {"No 'see' letters in here", 'c', -1}
  };
 
  size_t numtests = sizeof test / sizeof test[0];
  size_t i;
 
  char ch = 'o';
  int pos;
 
  for(i = 0; i < numtests; i++)
  {
    pos = strrindex(test[i].data, test[i].testchar);
 
    printf("Searching %s for last occurrence of %c.\n",
           test[i].data,
           test[i].testchar);
 
    printf("Expected result: %d\n", test[i].expected);
    printf("%sorrect (%d).\n", pos == test[i].expected ? "C" : "Inc", pos);
    if(pos != -1)
    {
      printf("Character found was %c\n", test[i].data[pos]);
    }
  }
 
  return 0;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部