NO

Author Topic: How to check all strings?  (Read 2988 times)

Offline bitcoin

  • Member
  • *
  • Posts: 179
How to check all strings?
« on: March 20, 2022, 10:51:18 PM »
There is a task, you need to compare a string with an array of strings. I don't know if I'm doing the right thing. It works, but I would like it to be somehow more elegant .. I think this solution is redundant. Or is it ok?
Code: [Select]
char *data[] = { "data1", "data2", "data3", "data4", NULL };
char *p;
UINT i = 0;
do
{
p = data[i];
/* doing something with string */
i++;
} while (p!=NULL);

Offline CLR

  • Member
  • *
  • Posts: 4
Re: How to check all strings?
« Reply #1 on: March 21, 2022, 01:34:03 AM »
Hi bitcoin. I think it is OK.

I'd write

Code: [Select]
for (int i = 0; data[i] != NULL; i++){ /* do something with data[i] */}

Offline 30f7r8d2

  • Member
  • *
  • Posts: 1
Re: How to check all strings?
« Reply #2 on: March 21, 2022, 05:46:29 AM »
Excuse me please but why there is NULL in *data[], isn't it an array of strings so there should be no need to NULL terminate it?

Code: [Select]
char *data[] = { "data1", "data2", "data3", "data4", NULL };

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
Re: How to check all strings?
« Reply #3 on: March 21, 2022, 08:25:42 AM »
This goes through strings.
Code: [Select]
#include <stdio.h>

char *data[] = { "data1", "data2", "data3", "data4", 0 };

int __cdecl main(void)
{
int i = 0;
while (data[i]) {
int j = 0;
while (data[i][j]) {
printf("%c ", data[i][j]);
j++;
}
printf("\n");
i++;
}
return 0;
}
Code: [Select]
d a t a 1
d a t a 2
d a t a 3
d a t a 4
May the source be with you

Offline bitcoin

  • Member
  • *
  • Posts: 179
Re: How to check all strings?
« Reply #4 on: March 21, 2022, 02:21:16 PM »
TimoVJL , CLR
Thank you !

Excuse me please but why there is NULL in *data[], isn't it an array of strings so there should be no need to NULL terminate it?

Code: [Select]
char *data[] = { "data1", "data2", "data3", "data4", NULL };

Because how I can guess , where is the end of array?
There may be a different number of string. Do not manually enter the count.

Offline AlexN

  • Global Moderator
  • Member
  • *****
  • Posts: 394
    • Alex's Link Sammlung
Re: How to check all strings?
« Reply #5 on: March 21, 2022, 04:09:16 PM »
You can try this:
Code: [Select]
char *data[] = {"data1", "data2", "data3", "data4"};
count = sizeof(data)/sizeof(data[0]);
or make a macro:
Code: [Select]
#define COUNT(x) (sizeof(x)/sizeof(x[0]))

char *data[] = {"data1", "data2", "data3", "data4"};
count = COUNT(data);
« Last Edit: March 21, 2022, 04:15:04 PM by AlexN »
best regards
 Alex ;)