C语言:尝试实现IndexOf 函数



我试着学习C Language,有些事情我不清楚。我想编写IndexOf函数,在string内搜索字符并返回Index号。我在ubuntu下运行它并使用以下内容进行编译:

test1: test.c
    gcc -g -Wall -ansi -pedantic test.c -o myprog1

这是我尝试过的:

int c;
int result;
    printf("Please enter string: ");
    scanf("%s", str1);
    printf("Please enter char: ");
    scanf("%d", &c);
    result = indexof(str1, c);
    printf("Result value: %dn", result);

这是我的函数:

int indexof(char *str, int c)
{
    int i;
    for (i = 0; i < strlen(str); i++)
    {
        if (str[i] == c)
            return i;
    }
    return -1;
}

所以我的问题是我的函数一直返回-1

scanf("%c",&c) ..您正在输入一个字符。

工作副本会像这样:-

char c; // you want to find the character not some integer. 
int result;
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf("%d", &c);
result = indexof(str1, c);
printf("Result value: %dn", result);

工作示例:-

#include <stdio.h>
#include <string.h>
 int indexof(char *str, char c)
    {
        int i;
        for (i = 0; i < strlen(str); i++)
        {
            if (str[i] == c)
                return i;
        }
        return -1;
    }
int main()
{
    char c;
    int result;
    char str1[100];
        printf("Please enter string: ");
        scanf("%s", str1);
        printf("Please enter char: ");
        scanf(" %c", &c);
        result = indexof(str1, c);
        printf("Result value: %dn", result);
}

由于c是 int:

int indexof(char *str, int c)
{
    int i;
    for (i = 0; i < strlen(str); i++)
    {
        if ((str[i]-'0') == c) // convert char to int
            return i;
    }
    return -1;
}

编写 IndexOf 函数,用于在字符串中搜索字符并返回索引号。

您可能想看看strchr()函数,该函数的使用如下所示:

/* Looks up c in s and  return the 0 based index */
/* or (size_t) -1 on error of if c is not found. */
#include <string.h> /* for strchr() */
#include <errno.h> /* for errno */
size_t index_of(const char * s, char c)
{
  size_t result = (size_t) -1; /* Be pessimistic. */
  if (NULL == s)
  {
    errno = EINVAL;
  }
  else
  {
    char * pc = strchr(s, c);
    if (NULL != pc)
    {
      result = pc - s;
    }
    else
    {
      errno = 0;
    }
  }
  return result;
}

你可以这样称呼它:

size_t index_of(const char *, char);
#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* for fprintf(), perror() */
#include <errno.h>  /* for errno */
int main(void)
{
  result = EXIT_SUCCESS;
  char s[] = "hello, world!";
  char c = 'w';
  size_t index = index_of(s, 'w');
  if ((size_t) -1) == index)
  {
    result = EXIT_FAILURE;
    if (0 == errno) 
    {
      fprintf("Character '%c' not found in '%s'.n", c, s);  
    }
    else
    {
      perror("index_of() failed");
    }
  }
  else
  {
    fprintf("Character '%c' is at index %zu in '%s'.n", c, index, s);  
  }
  return result;
}

最新更新