Easy Tutorial
❮ C Exercise Example79 C Exercise Example2 ❯

C Exercise Example 32

C Language Classic 100 Examples

Title: Remove a specified letter from a string, such as removing the letter 'a' from the string "aca".

Program Analysis: None.

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

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

// Function to delete specified letters from a string
char* deleteCharacters(char * str, char * charSet)
{
    int hash [256];
    if(NULL == charSet)
        return str;
    for(int i = 0; i < 256; i++)
        hash[i] = 0;
    for(int i = 0; i < strlen(charSet); i++)
        hash[charSet[i]] = 1;
    int currentIndex = 0;
    for(int i = 0; i < strlen(str); i++)
    {
        if(!hash[str[i]])
            str[currentIndex++] = str[i];
    }
    str[currentIndex] = '\0';
    return str;
}

int main()
{
    char s[2] = "a";     // Letter to be deleted
    char s2[5] = "aca";  // Target string
    printf("%s\n", deleteCharacters(s2, s));
    return 0;
}

The output of the above example is:

c

C Language Classic 100 Examples

❮ C Exercise Example79 C Exercise Example2 ❯