char * code片段

下面是我自己写的一个demo中操作字符一点代码片段, 查了不少关于char*操作的C函数资料, strtok ,strlcpy, strncpy, strstr, memcpy,strlen,strncpy 如果需要高效处理字符, 可以参照用法

const char *p; *p是const, p指向的内容不能改变
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结束,也不会增加\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函数会破坏被分解字符串的完整; 首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL ; [Linux内核]2.6.29后可用速度更快的strsep()代替
    
}    

while (1) {

    char *a = strstr(notparsed, "{");//strstr判断str2 是否是str1的子串, 这里是找出{在notparsed中出现的地址
    if (!a || strlen(a)==0) {
        break;
    }
    char *key = malloc(a-notparsed);
    strlcpy(key, notparsed, a-notparsed);//已知dest缓冲区足够的情况下,将src(含'\0'结束符)字符串复制到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中有\0,则即使没有复制到n个字符也会提前停止;只复制部分src内容, dest剩余空间不填充时 后面可能会输出乱字符. dest应该有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);

}

你可能感兴趣的:(char * code片段)