/** * Remove space from string at the beginning and end. * * @param src pointer to source string */ voidtrim(char *src) { int i; int len = strlen(src); int start = 0, end = len - 1;
while (start < end && src[start] <= ' ' && src[start] != 0) { start ++; }
while (end >= start && src[end] <= ' ' && src[end] != 0) { end --; }
/** * To get the index when sub string first appear in src. * * @param src src string * @param sub the string to search * @return the index of substring in source string, * otherwise return -1 if not exists */ intindex_of(constchar *src, constchar *sub) { char *result = strstr(src, sub);
return result ? strlen(src) - strlen(result) : -1; }
/** * To get the index when need string last appear in src. * * @param src src string * @param need the string to search * @return the index of substring in source string, * otherwise return -1 if not exists */ intlast_index_of(constchar *src, constchar *need) { int i; constchar *p = src + strlen(src); size_t len = strlen(need); char *buf;
for(i = 0; i < strlen(src); i ++) { buf = strchr(p --, *need); if (!buf) { continue; }
if (strncmp(buf, need, len) == 0) { returnstrlen(src) - strlen((char *)buf); } }
/** * Get sub string from source string. * * @param dest dest poniter to save string * @param src source string poniter * @param start the start index * @param end the end index */ voidsubstring(char *dest, constchar *src, int start, int end) { int i = start;
if (start > strlen(src)) { return; }
if (end > strlen(src)) { end = strlen(src); }
while (i < end) { dest[i - start] = src[i]; i ++; }
dest[i - start] = '\0'; }
5.starts_with 函数(检测字符串是否以某个字符串开头)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** * To check if the string start with specified string. * * @param src source string pointer * @param prefix prefix string poniter * @return ture if start with specified string, otherwise return false */ boolstarts_with(constchar *src, constchar *prefix) { int len = strlen(prefix); char buf[len];
substring(buf, src, 0, len);
return !strcmp(buf, prefix); }
6.ends_with 函数(检测字符串是否以某个字符串结尾)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/** * To check if the string end with specified string. * * @param src source string pointer * @param suffix suffix string poniter * @return ture if end with specified string, otherwise return false */ boolends_with(constchar *src, constchar *suffix) { int len = strlen(suffix); char buf[len];