下面是我自己寫的一個demo中操作字符一點代碼片段, 查了不少關(guān)于char*操作的C函數(shù)資料, strtok ,strlcpy, strncpy, strstr, memcpy,strlen,strncpy 如果需要高效處理字符, 可以參照用法
const char *p; *p是const, p指向的內(nèi)容不能改變
char * const p; p是const, p不能改變指向
-(void)parse{
NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
const char *notparsed = [cssStr UTF8String];
int len = strlen(notparsed)+1;//+1是因為strlen 不包含\0
char *p = malloc(len);
memcpy(p, notparsed, len);//memcpy會拷貝len個字符,不會因為遇到\0結(jié)束,也不會增加\0
char *step1_p = strtok(p, "}");//selector{a:b; c:d;}->{a:b;c:d;
while (step1_p) {
// printf("%s\n",step1_p);
[self step2Sep:step1_p intoDic:mdic];
step1_p = strtok(NULL, "}");//strtok函數(shù)會破壞被分解字符串的完整; 首次調(diào)用時,s指向要分解的字符串咐刨,之后再次調(diào)用要把s設(shè)成NULL ; [Linux內(nèi)核]2.6.29后可用速度更快的strsep()代替
}
while (1) {
char *a = strstr(notparsed, "{");//strstr判斷str2 是否是str1的子串, 這里是找出{在notparsed中出現(xiàn)的地址
if (!a || strlen(a)==0) {
break;
}
char *key = malloc(a-notparsed);
strlcpy(key, notparsed, a-notparsed);//已知dest緩沖區(qū)足夠的情況下,將src(含'\0'結(jié)束符)字符串復(fù)制到dest
char *b = strstr(a, "}");
char *value = malloc(b-a-1);
strlcpy(value, a+1, b-a-1);
NSString *keyStr = [NSString stringWithUTF8String:key];
NSDictionary *valueDic = [self parseValue:value];
[mdic setObject:valueDic forKey:keyStr];
//printf("value:%s\n",value);
notparsed = b+1;
}
const char *css_p = [cssStr UTF8String];
char *a = strstr(css_p, "{");
char *key = malloc(a-css_p);
strncpy(key, css_p, a-css_p);//如果src中有\(zhòng)0,則即使沒有復(fù)制到n個字符也會提前停止;只復(fù)制部分src內(nèi)容, dest剩余空間不填充時 后面可能會輸出亂字符. dest應(yīng)該有strlen(src)+1(\0)個字符長度, 最后一個字符不是\0時,要手動添加上\0
char *b = strstr(a, "}");
char *value = malloc(b-a);
strncpy(value, a+1, b-a-1);
printf("%p",a);
}