C String Problems and Solutions: From Basics to Advanced Logic

In the previous section we discussed the basics of C Strings. Now let us take a look at some real-life application Problems.

 

1. Write a C program to count vowels and consonants in a string.

				
					#include <stdio.h>

int main() {
    char str[100];
    int i, vowel = 0, constraint = 0;
    printf("Enter a string:");
    fgets(str, sizeof(str), stdin);

    for (i = 0; str[i] != '\0'; i++) {
        if (str[i]=='a'||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'||
            str[i]=='A'||str[i]=='E'||str[i]=='I'||str[i]=='O'||str[i]=='U')
            vowel++;
        else if ((str[i]>='a'&&str[i]<='z') || (str[i]>='A'&&str[i]<='Z'))
            constraint++;
    }
    printf("Vowels = %d\nConsonants = %d\n", vowel, constraint);
    return 0;
}

// Enter a string: qubrica
// Vowels = 3
// Consonants = 4

				
			
Index (i)Character str[i]CategoryLogicVowelsConsonants
0'q'Consonantelse if01
1'u'Vowelif11
2'b'Consonantelse if12
3'r'Consonantelse if13
4'i'Vowelif23
5'c'Consonantelse if24
6'a'Vowelif34
7'\n'NewlineNeither34
8'\0'NullTerminate34

2. Write a C program to find the frequency of a character in a string.

				
					#include <stdio.h>
int main() {
    char input_text[120], target;
    int index, occurrences = 0;

    printf("Please provide a sentence: ");
    scanf("%[^\n]", input_text);

    printf("Which character are you looking for? ");
    scanf(" %c", &target);

    // Iterating through the text 
    for (index = 0; input_text[index] != '\0'; index++) {
        if (input_text[index] == target) {
            occurrences++;
        }
    }
    printf("Total count of '%c': %d\n", target, occurrences);
    return 0;
}

// Please provide a sentence: qubrica
// Which character are you looking for? i
// Total count of 'i': 1

				
			
indexCharacterComparison (== 'i')Actionoccurrences
0'q'FalseSkip0
1'u'FalseSkip0
2'b'FalseSkip0
3'r'FalseSkip0
4'i'TrueIncrement1
5'c'FalseSkip1
6'a'FalseSkip1
7'\0'N/ATerminate1

3. Write a C program to remove all spaces from a string.

				
					#include <stdio.h>

int main() {
    char str[100];
    int i, j = 0;

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

    for (i = 0; str[i] != '\0'; i++) {
        if (str[i] != ' ')
            str[j++] = str[i];
    }
    // Null-terminate the modified string
    str[j] = '\0';

    printf("String without spaces: %s\n", str);
    return 0;
}

// Enter a string: C Program
// String without spaces: CProgram

				
			
Indexstr[i]Condition (!= ' ')ActionResulting str (First j chars)j value
0'C'Truestr[0] = 'C'C1
1" "FalseSkipC1
2'P'Truestr[1] = 'P'CP2
3'r'Truestr[2] = 'r'CPr3
4'o'Truestr[3] = 'o'CPro4
5'g'Truestr[4] = 'g'CProg5
6'r'Truestr[5] = 'r'CProgr6
7'a'Truestr[6] = 'a'CProgra7
8'm'Truestr[7] = 'm'CProgram8
9'm'Truestr[8] = 'm'CProgramm9
10'i'Truestr[9] = 'i'CProgrammi10
11'n'Truestr[10] = 'n'CProgrammin11
12'g'Truestr[11] = 'g'CProgramming12
13'\0'N/ATerminateCProgramming\012

4. Write a C program to check whether one string is a substring of another.

				
					#include <stdio.h>

int main() {
    char str[100], sub[100];
    int i, j, found = 0;

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

    for (i = 0; str[i] != '\0'; i++) {
        for (j = 0; sub[j] != '\0'; j++) {
            if (str[i + j] != sub[j])
                break;
        }
        if (sub[j] == '\0') {
            found = 1;
            break;
        }
    }

    if (found)
        printf("Substring found\n");
    else
        printf("Substring not found\n");

    return 0;
}

// Enter main string: qubrica
// Enter substring: rica
// Substring found
				
			
Outer Index (i)str[i]Inner Index (j)sub[j]Comparison (str[i+j] == sub[j])Actionfound
0'q'0'r''q' == 'r' (False)break inner loop0
1'u'0'r''u' == 'r' (False)break inner loop0
2'b'0'r''b' == 'r' (False)break inner loop0
3'r'0'r''r' == 'r' (True)Continue inner0
31'i''i' == 'i' (True)Continue inner0
32'c''c' == 'c' (True)Continue inner0
33'a''a' == 'a' (True)Continue inner0
34'\0'N/AInner loop ends1

5. Write a C program to convert all lowercase letters in a string to uppercase.

				
					#include <stdio.h>

int main() {
    char str[100];
    int i;

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

    for (i = 0; str[i] != '\0'; i++) {
        // Check if the character is a lowercase letter
        if (str[i] >= 'a' && str[i] <= 'z')
            str[i] = str[i] - 32; 
    }

    printf("Uppercase string: %s\n", str);
    return 0;
}

// Enter a string: qubrica
// Uppercase string: QUBRICA

				
			
Index (i)Character str[i]ASCII ValueCondition ('a' to 'z')Calculation (-32)New Character
0'q'113True113 - 32 = 81'Q'
1'u'117True117 - 32 = 85'U'
2'b'98True98 - 32 = 66'B'
3'r'114True114 - 32 = 82'R'
4'i'105True105 - 32 = 73'I'
5'c'99True99 - 32 = 67'C'
6'a'97True97 - 32 = 65'A'
7'\0'0FalseN/ATerminate

6. Write a C program to count the number of words in a string.

				
					console.log( 'Code is Poetry' );#include <stdio.h>

int main() { 
    char str[100];
    int i, count = 0;

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

    for (i = 0; str[i] != '\0'; i++) {
        // Increment count when a space is followed by a character
        if (str[i] == ' ' && str[i+1] != ' ' && str[i+1] != '\0')
            count++;
    }

    // Account for the first word if the string doesn't start with a space
    if (str[0] != ' ' && str[0] != '\0')
        count++;

    printf("Number of words = %d\n", count);
    return 0;
}

//Enter a string: I love Qubrica
// Number of words = 3

				
			
IndexCharacterLogic CheckResultcount
0'i'str[0] != ' 'First word detected1
1' 'str[1]==' ' && str[2]=='l'Space-to-Character transition2
2 - 5lovestr[i] != ' 'Characters skipped (no space)2
6' 'str[6]==' ' && str[7]=='q'Space-to-Character transition3
7 - 13qubricastr[i] != ' 'Characters skipped (no space)3
14'\0'str[14] == '\0'Loop termination3