NSString的字符串反转

这个是一个蛋疼的题目,当然蛋疼,当我给自己做了一个限定,正常在Obj-c中的操作都是NSString对象,如果不使用内置函数,那么要做算法,操作就是对象,正常人类的做法,当然应该使用一个NSMutableNString,用append去写。这样的话,你从前学的在C里面的算法一个屁都用不上,也可以交换两个前后两端的字符串,我心想都是一个但是其实那个索引的操作是不透明的,在一个正常的考试中,你也不会能够写一个东西去验证这个到底那个索引操作有多快。一个可控的方法,当然是还是用纯C来写。

        NSString *test = "this is a test";
        const char *p = [test cStringUsingEncoding:NSUTF8StringEncoding];
        int len = strlen(test);
        char *s = (void*)malloc(len+1);
        memset(s, 0×00, sizeof(len+1));
        strcpy(s, test);
        for(char *end = s + strlen(s) – 1; ; end > s ; –end , ++s){
             *s ^= *end;
                *end ^= *s;
                *s ^= *end;
       }
       NSString *result = [NSString stringWithUTF8String:s];
       free(s);

stackoverflow上的有两端交互的方法。

Share
Posted in Uncategorized at January 9th, 2012. No Comments.