C Exercise Example 32
Title:Delete specified letters from a string, for example: for the string "aca", delete the letter "a" in it.
Program analysis:None.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to delete the specified letter from a string
char* deleteCharacters(char* str, char* charSet) {
// Hash table used to store the characters to be deleted
int hash[256] = {0}; // Use an array of size 256 to store ASCII characters, initialized to 0
// If the character set to be deleted is empty, return the original string directly
if (charSet == NULL)
return str;
// Mark the characters to be deleted
for (int i = 0; i < strlen(charSet); i++)
hash[(unsigned char)charSet[i]] = 1; // Mark the ASCII code position of the character to be deleted as 1
int currentIndex = 0; // Used to track the current string index
// Delete the specified characters by traversing the string
for (int i = 0; i < strlen(str); i++) {
// If the current character is not in the character set to delete, keep it
if (!hash[(unsigned char)str[i]])
str[currentIndex++] = str[i];
}
str[currentIndex] = '\0'; // Add a null character at the end of the string to mark the end of the string
return str;
}
int main() {
char s[] = "a"; // The letter to delete
char s2[] = "aca"; // Target string
printf("%s\n", deleteCharacters(s2, s)); // Print the string after deleting the specified characters
return 0;
}
The output result of the above example is:
cother extensions