Open In App

C Program to Extract Characters From a String

Character extraction can be done by iterating through the string in the form of a character array. It basically means plucking out a certain amount of characters from an array or a string.

Now, to take input in C we do it by using the following methods:



Now the next step would be running the loop until we reach the null pointer, which exists in character arrays to indicate the end of the string. Being cautious, we will check for no blank space, if it is a valid character we print it using (“%c “,str[i]) else we will continue.

Example:






// C Program to demonstrate character
// extraction from a string
#include <stdlib.h>
#include <stdio.h>
int main()
{
    char str[20];
    printf("Enter the string: ");
    gets(str);
    // alternative scanf("%s",str);
   
    // character extraction
    printf("Printing the characters:: \n");
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] != ' ') { // not a white space
            printf("%c\n", str[i]); // printing each characters in a new line
        }
    }
    return 0;
}

Input:

GeeksforGeeks

Output:

Enter the string: GeeksforGeeks
Printing the characters:: 
G
e
e
k
s
f
o
r
G
e
e
k
s

Time Complexity: O(n) where n is the size of the string.

Auxiliary Space: O(1)

Article Tags :