Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Exercise 32

C Exercise 32

100 Classic C Language Examples 100 Classic C Language Examples

**Problem:** Delete a specified letter from a string. For example, in the string "aca", delete the letter a.

**Analysis:** None.

Example

// Created by www.runoob.com on 15/11/9.

// Copyright (c) 2015 Runoob Tutorial. All rights reserved.

//

#include

<

stdio.h

#include

<

stdlib.h

#include

<

string.h

// Function to delete a 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 set of characters to delete 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 each 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 set of characters 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 its termination

return

str

;

}

int

main

(

)

{

char

s

[

]

=

"

a

"

;

// The letter to delete

char

s2

[

]

=

"

aca

"

;

// The target string

printf

(

"

%s

\

n

"

,

deleteCharacters

(

s2

,

s

)

)

;

// Print the string after deleting the specified characters

return

0

;

}

The output of the above example is:



c

100 Classic C Language Examples 100 Classic C Language Examples