C program to print indexes of a particular character in a string

In this program we will read a string and print indexes of a particular character in C language, for example, if input string is "Hi there, how are you?" and we want to print the indexes of character ‘o’ then program will return 11 and 19, because ‘o’ exists on both indexes.

Program to get the indexes of a particular characters in C

#include <stdio.h>

int main() {
  char str[30], ch;
  int ind[10], loop, j;

  printf("Enter string: ");
  scanf("%[^\n]s", str);

  printf("Enter character: ");
  getchar();
  ch = getchar();

  j = 0;
  for (loop = 0; str[loop] != '\0'; loop++) {
    if (str[loop] == ch)
      ind[j++] = loop;
  }

  printf("Input string is: %s\n", str);
  printf("Indexes: ");
  for (loop = 0; loop < j; loop++)
    printf("%d \t", ind[loop]);

  return 0;
}

Output

Enter string: Hi there, how are you?
Enter character: o
Input string is: Hi there, how are you? 
Indexes: 11	 19

In this example, we have used the following C language topics that you should learn:

C String Programs »


Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.