C語言字串常用處理技巧總結
阿新 • • 發佈:2018-12-17
1.從一串字串中提取中間一段,並單獨拿出來
char *pStart = NULL,*pMid = NULL,*pEnd = NULL,*t = NULL;
pStart= strstr(pStart, "A");
pEnd = strstr(pStart, "B");
tempLen = pEnd - pStart;
t = (char *)malloc(tempLen + 1);//注意留一個空間給結束符
memcpy(t, pStart, tempLen);
t[tempLen] = '\0';
2.比較字串,不區分大小寫
/***************************************************************************** * FUNCTION * Tr_wcsncmp * DESCRIPTION * 指定長度比較字串,不區分大小寫 * PARAMETERS * void * RETURNS * void *****************************************************************************/ #define ISBIGAZ(c) (c >= 'A' && c <= 'Z') #define ISSMALLAZ(c) (c >= 'a' && c <= 'z') int Tr_wcsncmp(const char* ch1, const char *ch2, int len) { int i=0, j=0 ; for (i=0; i<len; i++) { if(0==Tr_wccharcmp(ch1[i],ch2[i])) j++; else break; } if (j == len) return 0; else return 1 ; } /***************************************************************************** * FUNCTION * Tr_wcscmp * DESCRIPTION * 比較字串,不區分大小寫 * PARAMETERS * void * RETURNS * void *****************************************************************************/ int Tr_wcscmp(const char* ch1, const char *ch2) { const char *s1 = ch1; const char *s2 = ch2; char c1, c2; do { c1 = *s1++; c2 = *s2++; if (c1 == '\0') return c1 - c2; } while (0==Tr_wccharcmp(c1,c2)); return c1 - c2; } /***************************************************************************** * FUNCTION * Tr_wccharcmp * DESCRIPTION * 比較字元,不區分大小寫 * PARAMETERS * void * RETURNS * void *****************************************************************************/ tracker_int8 Tr_wccharcmp(const char ch1, const char ch2) { tracker_int8 ret = 1; if (ch1 == ch2 ) { ret =0; } else if( ISBIGAZ(ch1) || ISSMALLAZ(ch2) ) { if (ch1 + 32 == ch2 ) ret = 0; } else if ( ISBIGAZ(ch2) || ISSMALLAZ(ch1) ) { if (ch2 + 32 == ch1) ret = 0; } return ret; }
3.字串ch1中,查詢第n個ch2,返回第n個ch2的頭地址
/***************************************************************************** * FUNCTION * Tr_n_strstr * DESCRIPTION * 字串ch1中,查詢第n個ch2,返回第n個ch2的頭地址 * PARAMETERS * void * RETURNS * void *****************************************************************************/ char* Tr_n_strstr(const char* ch1, const char *ch2, int n) { /*----------------------------------------------------------------*/ /* Local Variables */ /*----------------------------------------------------------------*/ char *token_pos = NULL; /*----------------------------------------------------------------*/ /* Code Body */ /*----------------------------------------------------------------*/ token_pos = strstr(ch1,ch2); //strstr(str1,str2) 函式用於判斷字串str2是否是str1的子串。如果是,則該函式返回str2在str1中首次出現的地址;否則,返回NULL。 n--; while (token_pos !=NULL && n>0) { token_pos = strstr(token_pos+strlen(ch2),ch2); n--; } return token_pos; }