Is there function in a C library that iterates through an array and checks if two characters are next to each other?
For example : array[30] = "example@.com"
Is it possible to go through the array and check if '@' and '.' are next to each other?
Is there function in a C library that iterates through an array and checks if two characters are next to each other?
For example : array[30] = "example@.com"
Is it possible to go through the array and check if '@' and '.' are next to each other?
Use strstr
:
if (strstr(array, "@.") || strstr(array, ".@"))
/* the characters are touching */
Is there function in a C library that iterates through an array and checks if two characters are next to each other?
No.
As OP asked about an array and not a string, a strstr()
approach will not work.
Use the below, works even if either/both c2, c2
are '\0'
.
bool two_char_check(const char *s, size_t n, char c1, char c2) {
const char *original = s;
while (n > 0) {
char *s1 = memchr(s, c1, n);
if (s1 == NULL) {
return false;
}
if (s1 != original && s1[-1] == c2) {
return true;
}
size_t offset2 = (size_t) (s1 - s) + 1;
if (offset2 < n && s1[1] == c2) {
return true;
}
s += offset2;
n -= offset2;
}
return false;
}
int main(void) {
char array[30] = "example@.com";
// expect true
printf("%d\n", two_char_check(array, sizeof array, '@', '.'));
printf("%d\n", two_char_check(array, sizeof array, 'm', '\0'));
printf("%d\n", two_char_check(array, sizeof array, '\0', 'm'));
printf("%d\n", two_char_check(array, sizeof array, '\0', '\0'));
// expect false
printf("%d\n", two_char_check(array, sizeof array, 'x', '\0'));
printf("%d\n", two_char_check(array, sizeof array, '@', 'E'));
printf("%d\n", two_char_check(array, sizeof array, 'M', '\0'));
}