C语言:尝试实现IndexOf函数

C language: try to implement IndexOf function

我尝试学习 C Language 但有些事情我不太清楚。 我想编写 IndexOf 函数在 string 和 return 中搜索 char 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: %d\n", result);

这是我的职能:

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

    return -1;
}

所以我的问题是我的函数 return -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: %d\n", 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: %d\n", result);

}

因为 c 是整数:

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;
}

write IndexOf function that search for char inside string and return the Index number.

您可能想看看 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;
}