Search string specified by the first parameter for the first occurrence of a character specified by the second parameter - C String

C examples for String:String Function

Description

Search string specified by the first parameter for the first occurrence of a character specified by the second parameter

Demo Code

#include <stdio.h>

#define LIMIT 50//from  ww  w  .java2s.  c  o  m

char * findchar(char *str, const char ch);

int main(void){
  char string[LIMIT];
  char *chloc;
  char ch;

  printf("Enter a string to search: ");
  fgets(string, LIMIT, stdin);
  while (string[0] != '\n'){
    printf("Enter a character to search for: ");
    ch = getchar();
    // discard rest of line if any
    if (ch != '\n')
      while (getchar() != '\n')
        continue;

    chloc = findchar(string, ch);
    if (chloc == NULL)
      printf("Character %c not found in %s", ch, string);
    else
      printf("Character %c found  at index %lu in %s", ch, chloc - string, string);

    // get new input
    printf("Enter a string to search (empty line to quit): ");
    fgets(string, LIMIT, stdin);
  }

  puts("Bye");

  return 0;
}
// find and return pointer to first occurrence of char ch in string str. return NULL if not found
char * findchar(char *str, const char ch){
  while (*str != '\0'){
    if (*str == ch)
      return str;
    str++;
  }

  // if ch is not found, return null
  return NULL;
}

Result


Related Tutorials