How to check all strings?

Started by bitcoin, March 20, 2022, 10:51:18 PM

Previous topic - Next topic

bitcoin

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?
char *data[] = { "data1", "data2", "data3", "data4", NULL };
char *p;
UINT i = 0;
do
{
p = data[i];
/* doing something with string */
i++;
} while (p!=NULL);

CLR

Hi bitcoin. I think it is OK.

I'd write


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

30f7r8d2

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?

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

TimoVJL

This goes through strings.
#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;
}
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

bitcoin

TimoVJL , CLR
Thank you !

Quote from: 30f7r8d2 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?

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.

AlexN

#5
You can try this:
char *data[] = {"data1", "data2", "data3", "data4"};
count = sizeof(data)/sizeof(data[0]);

or make a macro:
#define COUNT(x) (sizeof(x)/sizeof(x[0]))

char *data[] = {"data1", "data2", "data3", "data4"};
count = COUNT(data);
best regards
Alex ;)