C Program to Print all the Integers in a Sentence

In this post, we will discuss how to print all the integers in a sentence in C language.

Example,

Input
Hello 124 892.12 World Smith John 974

Output
124
974

Steps

  1. Let str be the input string.
  2. Let temp be a temporary string
  3. Initialize i = 0, j = 0 and n = str.LENGTH
  4. Repeat the following steps while i < n
    1. If str[i] is a digit
      • Set j = 0
      • Repeat the following steps while i < n AND str[i] is a digit
        • temp[j] = str[i]
        • ++i, ++j
      • If str[i] is blank ( ‘ ‘ ) OR i == n then
        • Print temp (till j)
    2. Repeat the following steps while i < str.LENGTH and str[i] not blank character ( ‘ ‘ ).
      • ++i
    3. ++i
  5. Terminate the program.

Basically, what we are doing is whenever we encounter a word that starts with a digit, we keep reading the word until we reach a non-digit character. If the non-digit character is a blank or end of string character then it means that the word only contains digits. Hence, the word we just scanned is an integer.

Program to Print all the Integers in a Sentence

#include <stdio.h>
#include <string.h>

int main() {

	char str[100];	// input string
	char temp[100];	// temporary string
	int i = 0, j = 0, n;

	printf("Enter a sentence: ");

	gets(str);	// enter string

	n = strlen(str);	// n stores length of input string

	while (i < n) {

		if (str[i] >= '0' && str[i] <= '9') {

			j = 0;

			// if we enounter a digit, then
			// we keep storing the digits in the temporary array
			// until we encounter a non-digit character
			while (i < n && str[i] >= '0' && str[i] <= '9') {
				temp[j] = str[i];
				++j, ++i;
			}

			// if str[i] is a blank or i==n
			// then it means that the word stored in temp
			// is a complete integer, thus we print temp
			if (str[i] == ' ' || i == n) {
				temp[j] = '\0';
				puts(temp);
			}

		}

		while (i < n && str[i] != ' ')
			++i;

		++i;

	}

}

Output

Enter a sentence: Hello 124 892.12 World Smith John 974 hello999 40

Integers in the string:-
124
974
40

Read

Leave a Comment

Your email address will not be published.