pr0jectgamer
pr0jectgamer

Reputation: 21

How does strcmp work in C in this case? I have an array to loop through and a char which needs to be compared with each element in the array

I have a array called notes which is

char *NOTES[] = {"A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"};

I then need to implement a function which gets the notes index

int get_note_index(char* string) {}

I thought of using the strcmp pre-written method to compare the parameter passed into the argument which is string and the elements of the notes array.

I did something like strcmp(string,NOTES[i]) where i is incremented with a for loop.

Note: the string passed is a note itself, such as A where the output would be 0, since after a successful comparison NOTES[0] would match with the argument string. 1 for "Bb" and so on.

I'm new to C so I don't know how to effectively use strcmp() or if it can even be used like this.

Upvotes: 0

Views: 1110

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

The function declaration should look like

size_t get_note_index( const char *a[], size_t n, const char *s ); 

That is you have to pass the number of elements in the array that will be used in a loop within the function.

If the string is not found then the function returns the position after the last element of the array.

Here is a demonstrative program.

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

size_t get_note_index( const char *a[], size_t n, const char *s ) 
{
    size_t i = 0;

    while ( i < n && strcmp( a[i], s ) != 0 ) ++i;

    return i;
}

int main(void) 
{
    const char * NOTES[] = 
    {
        "A", "Bb", "B", "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab"
    };

    const size_t N = sizeof( NOTES ) / sizeof( *NOTES );

    const char *s = "Db";

    size_t pos = get_note_index( NOTES, N, s );

    if ( pos != N )
    {
        printf( "The index of the string \"%s\" is %zu\n", s, pos );
    }
    else
    {
        printf( "The string \"%s\" is not found\n", s );
    }

    s = "Bd";

    pos = get_note_index( NOTES, N, s );

    if ( pos != N )
    {
        printf( "The index of the string \"%s\" is %zu\n", s, pos );
    }
    else
    {
        printf( "The string \"%s\" is not found\n", s );
    }

    return 0;
}

The program output is

The index of the string "Db" is 4
The string "Bd" is not found

Upvotes: 1

John Carter
John Carter

Reputation: 6995

your solution will resemble:

int get_note_index(char* string) {

   for (int i = 0; i < 12; i++) {
      if (strcmp(string, NOTES[i]) == 0) {
         return i;
      }
   }

  return -1; // not found
}

You may want to replace 12 with a #define for the size of the tone row. Here I return -1 if the note doesn't match.

Upvotes: 0

Related Questions