Count how many times each character appears in a string (no function use)

Asked

Viewed 5,608 times

-2

I’m having the doubt in a matter of string exercises that I’m doing. The question is this below:

Write a program that reads a string and prints how many times each character

appears in this string

1st string:

TTAAC

Upshot:

T: 2X
A: 2X
C: 1X

Remembering that it cannot be done using any function.

  • 1

    You can use a 0 initialized vector in all 128 houses and then for each letter l do count[l]++

  • Without using native C function, or without creating a function to do so?

  • Stackoverflow does not distribute code, just fix or review

  • @Jeffersonquesado to using 2 is to make the comparison of one inside the other to and adding to see if you can pull the sum, it seems that is flowing, the way you sent there! Thank you

  • I’m pretty sure this is duplicated, but I haven’t been able to find it yet. I’ve seen this question a few times around

2 answers

0

Here is an example of how to count occurrences of the same character present in a string in C. (This example does not consider 'A' and 'a' chars equal').

#include "stdio.h"
#include "stdlib.h"

int isAlpha(char c) {
  if(c >= 48 && c <= 57) { // [0-9]
    return 1;
  }

  if(c >= 65 && c <= 90) { // [A-Z]
    return 1; 
  }

  if(c >= 97 && c <= 122) { // [a-z]
    return 1;
  }

  return 0;
}

int main(void) {
    int *map = (int *)calloc(128, sizeof(int));
    int i = 0;

    char *test = "banana";
    char tmp;

    do {
        tmp = test[i++];
        if (isAlpha(tmp)) {
            map[tmp]++;
        }
    } while (tmp != '\0');

    for (i = 0; i < 128; i++) {
        if (map[i] != 0) {
            printf("%c = %d\n", i, map[i]);
        }
    }

    return 0;
}

-1


Code finalized!! EDITED

#include <stdio.h>

main(){
    char str[30];
    int i, j, count = 0, aux = 0, c = 1;

    puts("Informe a String");
    gets(str);

    while (str[count] != '\0'){
        count++;
    }

    for(i = 0; i < count; i++){ 
        aux = 1; 
        for(j = i + 1; j < count; j++){ 
            if(str[i] == str[j]){ 
                aux++; 
            } else
                break;
        }   
        if(i == 0) 
          c = 1; 
        else{
          for(j = i - 1; j >= 0; j--){ 
            if(str[i] != str[j])
              c = 1;
            else{ 
              c = 0;
              break;
            }
          }
        }
        if(c == 1)
        printf("\n%c : %d", str[i], cont);
    }


}
  • 1

    This answer does not present the correct result for banana, or even ana

  • @Jeffersonquesado Code corrected!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.