开发者

In C, how to remove all characters present in one array from another array?

开发者 https://www.devze.com 2023-02-14 13:52 出处:网络
In C, how to re开发者_StackOverflowmove all characters present in one array from another array?Sounds like homework but here\'s a solution.

In C, how to re开发者_StackOverflowmove all characters present in one array from another array?


Sounds like homework but here's a solution.

Make an array of 256 entries, like char set[256]. Read the first string. For each character c set set[(unsigned char)c] to 1. Read and copy the second string. For each character c if set[c] then skip c.

I forgot and left out that you must first memset(set, 0, sizeof(set)) before setting any of its values to 1.


If they are numbers:

You can not "remove" them, but you can either set them to 0 (or any other value that can represent removal in your case) or create a new array which contains the numbers which do not belong in the subset of the two arrays.

The brute force way is to use two nested for loops

if they are chars:

you may "remove" them by "shifting"-"swapping"-"moving" all characters which do not belong in the common subset in the left, and then set the null terminator in the right place. (as long you do not mess with string literals (char * p = "lala") this is fine). This will pretty much make the chars who are common to disappear.


Assume you want to remove the chars in a0 that exist in a1. First create a boolean array where each index is a character. ex. x['c'] would be true if 'c' is found in a1. Then loop through a0, checking the x array to see if a char should be kept or tossed. You can create a new array with elements removed if needed. This should be a O(n) operation.


void remove_repeated(char* s, char* another)
{
    // ... preparation with another... see other answers
    for (pos = p = s; *p != 0; p++)
    {
        if (!macro_is_repeated(*p))
           *pos++ = *p;
    }
    *pos = 0;
}

See other answers for the is_repeated part.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号