João Sacramento
João Sacramento

Reputation: 83

Counting the number of times a letter appears in a String -> Assembly

Imagine I have a program in C that gives me a string. For example, "stackoverflow rocks".

Now I want create a function in Assembly that will count, for example, how many times the letter "o" appears in my string.

This function will be called at the C program.

I was thinking to create a program in C that would made me this and then convert it to Assembly trough the flag -s.

[EDIT] Ok, I did this:

#include<stdio.h>

int FindChar(char *ptr, char toFind);

int FindChar(char *ptr, char toFind){

    int num;

    for (int i=1; ptr[i]=0; i++)
        if (ptr[i] = toFind){
            num++;
        }

    return(num);
}

int main ( ) {

    char str[]=”stackoverflow rocks”; 
    char tf=”o”; 
    printf(“It appears %d times \n”, FindChar(str,tf));
}

What's wrong with my function?

Upvotes: 1

Views: 887

Answers (1)

mossjm
mossjm

Reputation: 273

I think that your alternate double quote characters are causing the errors, plus your initialization of char tf should use single quotes, not double quotes, since it is a char not a string.

As harold pointed out earlier, the = needs to be a == so it functions properly as a comparison.

You also don't need to have the additional i variable, you can just advance the pointer. Since you are wanting assembly code anyways, it should make it a bit shorter and also technically be more efficient.

This code fixes the errors and also should be functionally sound:

#include<stdio.h>

int FindChar(char *ptr, char toFind);

int FindChar(char *ptr, char toFind){
  int num = 0;
  for ( ; *ptr != '\0'; ++ptr)
    {
      if (*ptr == toFind){
        ++num;
      }
    }
  return(num);
}

int main ( ) {
  char str[]="stackoverflow rocks";
  char tf='o';
  printf("It appears %d times \n", FindChar(str,tf));
}

Upvotes: 1

Related Questions