C language learning to delete redundant elements of character arrays

1. Understand the principle

If there is a character array abbbcaddd, how to make this array delete the redundant same characters, and finally abcd?

Here we first use sizeof to calculate the size of the array, and then divide by the value of a character size through sizeof to calculate how many elements the character has.

The first is to traverse through two for loops, and find which characters are the same by traversing the inner layer through the outer layer:

 After the outer layer finds a, the inner loop searches for each one, but the first value found cannot be deleted, so if the value of the inner loop is the value of the outer loop + 1, that is:

 Then when we find two identical characters, we need to continue to search and delete them, because there are 3 b, we can't just delete one, so:

 Then every time a character is deleted, the value of the array can be reduced, the code is as follows:

#include<stdio.h>
int main()
{
    char words[] = "abbbcadddd";
    int len = sizeof(words) / sizeof(words[0]);
    for (int i = 0; i < len-1; i++)
    {
        for (int k = i + 1; k < len - 1;)
        {
            if (words[i] == words[k])
            {
                for (int t = k; t < len - 1; t++)
                {
                    words[t] = words[t+1];
                }
                len--; //数组的长度-1
            }
            else
            {
                k++;
            }
        }
    }
    puts(words);

    return 0;
}

Guess you like

Origin blog.csdn.net/q244645787/article/details/126615745