Latest web development tutorials

C Exercise Example 32

100 cases of classic C language 100 cases of classic C language

Topic: Deleting a string at a specified letters, such as: the string "aca", delete them a letter.

Program Analysis: None.

Source Code:

//  Created by www.w3big.com on 15/11/9.
//  Copyright © 2015年 本教程. All rights reserved.
//

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

// 删除字符串中指定字母函数
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";     // 要删除的字母
    char s2[5] = "aca";  // 目标字符串
    printf("%s\n", deleteCharacters(s2, s));
    return 0;
}

The above example output is:

c

100 cases of classic C language 100 cases of classic C language