Reputation: 13
I need to parse my string but my delimiters are all characters excepts a-z and A-Z. How can I do that?
I thought strtok but I must write all character as delimiter and it would be too long. Exampe string:
Ax'cda2hsa+AsF(f/a as
It needs to be split into: "Ax" "cda" "hsa" "AsF" "f" "a" "as"
Is there any parsing function in C libraries which i can write my all delimeters as an interval ?
Upvotes: 0
Views: 323
Reputation: 1866
you can just walk thru the string and do that yourself if you don't want to do regex(3)
#include <stdio.h>
#include <string.h>
int main(int ac, char *av[]) {
char string[] = " Ax'cda2hsa+AsF(f/a as";
int i,idx,len;
len = strlen(string);
#define MAX_SPLIT 256
#define MAX_SPLIT_MASK (MAX_SPLIT - 1)
char buf[MAX_SPLIT];
for (idx = 0, i=0;i<len;i++) {
char c = string[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <='Z')) {
buf[idx++ & MAX_SPLIT_MASK] = c;
} else {
buf[idx++ & MAX_SPLIT_MASK] = '\0';
if (idx > 1)
printf("%s\n",buf);
idx = 0;
}
}
if (idx > 1) {
buf[idx++ & MAX_SPLIT_MASK] = '\0';
printf("%s\n",buf);
}
#undef MAX_SPLIT
#undef MAX_SPLIT_MASK
return 0;
}
Upvotes: 1
Reputation: 409482
Use strpbrk
to find the start of valid characters, and then strspn
to get the length. Extract into new string. Repeat until strpbrk
returns NULL
.
Upvotes: 0
Reputation: 11162
If you're looking for a c library function, strspn(str, dict)
is useful. It returns the length of the first substring of str containing only characters in dict. Thus,
strspn("hello world", "leh");
Would return 4.
Upvotes: 1