How to get element index of an array?

Good morning,

I am working on a project where I need to get the element index of an array. The following may clarify this:

char cti[]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

If I need the placement number of "5" (which is 6), how do I find this?

Let me know if you need more clarification

Single quotes, not double.

You could look at strchr.

index of '5' is 5, indexes starts from zero

It depends on what @algorithmmusic is talking about.

If you want to find the character 'X' in an array of chars, by hand, you can use a for loop to see if the character at an index i is equal to the character you are looking for.

If you made cti into a properly terminated string, an array of characters with a '\0' in the last index, you could use strchr().

strchr() returns a pointer; to get the index, you must subtract the base array address.

char cti[]={'0', '1', '2', 'A', '4', '5', '6', '7', '8', '9', '\0'};

void setup()
{
  Serial.being(115200);

  Serial.println(cti[3]);

// find 'A'

  char *x = strchr(cti, 'A');
  int index = x - cti;
  Serial.println(index); 
}

void loop()
{
}

HTH

a7

you can use a loop to search for the element, e.g.

void setup() {
  Serial.begin(115200);
  int i;
  char cti[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }, find='5';
  for (i = 0; i < sizeof(cti); i++)
    if (cti[i] == find) {
      Serial.printf("index of %c is %d\n", find, i);
      break;
    }
  if (i == sizeof(cti)) Serial.printf("%c not found\n", find);
}
void loop() {
  // put your main code here, to run repeatedly:
}

a run on an ESP32 gives

index of 5 is 5
1 Like

How did I forget that :person_facepalming:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.