c) To print out the number of alphabets in the string

Asked 2 years ago, Updated 2 years ago, 39 views

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

int main(void)

{

char *src = "aaabbb";

char* output="a";

char eng[26] = { 0 }; 

char string[10] = { 0 };

for (int i = 'a'; i <= 'z'; i++)

{

int count = 0;

    for (int j = 0; j < strlen(src); j++)
    {
        if (i == src[j])
        {
            count++;
            int index = (int)i-97;
            eng[index] = count; 
        } //Save as many alphabets as possible
    }

}
printf("src=%s\n", src);
for (int i= 'a'; i <= 'z'; i++)
{
    if (eng[(int)i-97] > 0)
    {

        sprintf(string, "%c%d", (char)i, eng[(int)i-97]);
        strcpy(output, string);

    }

}
printf("%s", output);

return 0;
}

The string aaabbb is initialized in src. I want to save this as a3b3 in the string variable output. So I'm trying to paste the string into the empty string output in the last for statement, but there's an error in that part. I think output is the problem, how should I change it?

c string

2022-09-20 19:54

1 Answers

The output should point to a space where data can be changed. The code above points to an unchangeable string of "a".

Array must be utilized or memory dynamic allocation must be utilized.

Please refer to the code below.

#define _CRT_SECURE_NO_WARNINGS

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

int main(void)
{
    char* src = "aaabbb123gghihiqqq";
    char output[20] = { 0, };
    char eng[26] = { 0, };
    char string[10] = { 0, };

    for (int i = 'a'; i <= 'z'; i++)
    {
        int count = 0;

        for (size_t j = 0; j < strlen(src); j++)
        {
            if (i == src[j])
            {
                count++;
                int index = (int)i - 97;
                eng[index] = count;
            } //Save as many alphabets as possible
        }
    }
    printf("src=%s\n\n", src);
    for (int i = 'a'; i <= 'z'; i++)
    {
        if (eng[(int)i - 97] > 0)
        {
            sprintf(string, "%c%d", (char)i, eng[(int)i - 97]);
            strcpy(output, string);
            printf("%s\n", output);
        }
    }

    return 0;
}


2022-09-20 19:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.