Problem Solving using C Language

0 of 76 lessons complete (0%)

Strings

Lab: Advanced String Operations

1. Program to Remove All Duplicate Characters from a String

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

int main() {
    char str[100], result[100] = {0};
    int flag[256] = {0};  // ASCII characters table
    int j = 0;

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

    for (int i = 0; str[i] != '\0'; i++) {
        if (flag[(unsigned char)str[i]] == 0) {
            result[j++] = str[i];
            flag[(unsigned char)str[i]] = 1;
        }
    }
    result[j] = '\0';  // Null terminate the result string

    printf("String after removing duplicates: %s\n", result);

    return 0;
}

2. Program to Count the Occurrences of a Substring in a Given String

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

int main() {
    char str[100], subStr[50];
    int count = 0;
    char *pos;

    printf("Enter the main string: ");
    scanf("%[^\n]s", str);
    getchar();  // Clear the buffer
    printf("Enter the substring: ");
    scanf("%[^\n]s", subStr);

    pos = strstr(str, subStr);
    while (pos != NULL) {
        count++;
        pos = strstr(pos + 1, subStr);
    }

    printf("Occurrences of '%s': %d\n", subStr, count);

    return 0;
}

3. Program to Replace a Substring in a String with Another Substring

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

void replaceSubstring(char *str, char *subStr, char *replaceStr) {
    char result[200] = {0};  // Buffer to store result
    char *pos, *start = str;
    int lenSub = strlen(subStr);

    while ((pos = strstr(start, subStr)) != NULL) {
        // Append part before the substring
        strncat(result, start, pos - start);
        // Append the replacement substring
        strcat(result, replaceStr);
        // Move start pointer beyond the found substring
        start = pos + lenSub;
    }
    // Append remaining part of the original string
    strcat(result, start);

    printf("String after replacement: %s\n", result);
}

int main() {
    char str[100], subStr[50], replaceStr[50];

    printf("Enter the main string: ");
    scanf("%[^\n]s", str);
    getchar();  // Clear the buffer
    printf("Enter the substring to replace: ");
    scanf("%[^\n]s", subStr);
    getchar();  // Clear the buffer
    printf("Enter the replacement substring: ");
    scanf("%[^\n]s", replaceStr);

    replaceSubstring(str, subStr, replaceStr);

    return 0;
}

4. Program to Find Digits and Add Them Up in a String

#include <stdio.h>
#include <ctype.h>

int main() {
    char str[100];
    int sum = 0;

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

    for (int i = 0; str[i] != '\0'; i++) {
        if (isdigit(str[i])) {
            sum += str[i] - '0';
        }
    }

    printf("Sum of digits in the string: %d\n", sum);

    return 0;
}