How to find first occurrence of a character in a string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
  
int first_occurrences(char s[], char ch) {
    int i  = 0, len = strlen(s);
     while(i < len && s[i] != ch)
        i++;
    return (i == len) ? -1: i;
}
  
int main() {
    char s[] = "c c++ c# java php python cobol";
      
    printf("%d\n", first_occurrences(s, 'c'));
    printf("%d\n", first_occurrences(s, 'p'));
    printf("%d\n", first_occurrences(s, 'x'));
      
    return 0;
}
   
   
        
/*
run:
     
0
14
-1
  
*/

 



answered Jul 5, 2020 by avibootz
edited Jul 5, 2020 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
   
int main() {
    char s[] = "c c++ c# java php python cobol";
    
    char *p = memchr(s, 'a', strlen(s));
    printf("%d\n", p - s);
    
    p = memchr(s, '+', strlen(s));
    printf("%d\n", p - s);

    return 0;
}
    
    
         
/*
run:
      
10
3
   
*/

 



answered Dec 25, 2020 by avibootz
...