[程式設計師日記]16題了解OC字串

weixin_34194087發表於2015-12-26
  1. 查詢一個字串2在字串1中出現的次數

      -(NSUInteger)countOfString:(NSString *)str1 withSubstring:(NSString *)str2
      {
         NSArray * arr = [str1 componentsSeparatedByString:str2];
         return [arr count] -1 ;
      }
    
  2. 輸入一段字串,統計其中的單詞個數
    比如:輸入 I like China 輸出:3
    -(NSUInteger)countOfWordInString:(NSString *)str
    {
    NSArray * arr = [str componentsSeparatedByString:@" "];
    int count = 0;
    for (NSString * obj in arr) {
    if (![obj isEqualToString:@""] ) {
    count++;
    }
    }
    return count;
    }

  3. 判斷字串str是否是合法的C變數,比如不能數字開頭,只能字串和等開頭
    #define REGULAROFIFFOR3_1 (c >= 'a' && c<='z')||(c>='A'&&c<='Z')||(c=='
    ')
    #define REGULAROFIFFOR3_2 (c >= 'a' && c<='z')||(c>='A'&&c<='Z')||(c>='1'&&c<='9')||(c=='_')
    -(BOOL)isCValidVar:(NSString *)str
    {
    char c = [str characterAtIndex:0];
    if (!(REGULAROFIFFOR3_1)) {
    return NO;
    }
    for(int i = 1; i < [str length]; i++)
    {
    c = [str characterAtIndex:i];
    if (!(REGULAROFIFFOR3_2)) {
    return NO;
    }
    }
    return YES;
    }

  4. 陣列排序 arr陣列中包含的是NSString字串單詞
    在英語類的App很多時候按照最後一個單詞進行排序.
    將陣列arr進行按照單詞 最後一個字母進行升序排序(注意 最後一個字母),比如arr中是(hello, world,apple,demo)
    返回是(world, hello,apple, demo) 如果最後一個字母相同,就按照倒數第二個,以此類推

       -(NSArray *)sortWord:(NSArray *)arr
       {
           NSMutableArray * marr = [NSMutableArray arrayWithArray:arr];
           [marr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
               long objLen1 = [obj1 length];
               long objLen2 = [obj2 length];
               long top = objLen1<objLen2 ? objLen1:objLen2;
               for ( int i = 1 ; i < top; i++) {
                   NSComparisonResult result = [[obj1 substringWithRange:NSMakeRange(objLen1-i, 1)] compare:[obj2 substringWithRange:NSMakeRange(objLen2-i, 1)]];
                   if (result != 0) {
                       return result;
                   }
               }
               return NSOrderedSame;
           }];
           return marr;
       }
    
  5. 取得檔案的副檔名
    比如 傳入字串 @"/home/apple/oc.txt" 返回:@"txt"
    傳入字串 @"/usr/apple/ios.m" 返回:@"m"
    - (NSString *)extensionOfFilePath:(NSString *)path
    {
    NSArray * arr = [path componentsSeparatedByString:@"."];
    return [arr objectAtIndex:[arr count]-1];
    }

6.將一個字串陣列中的元素組合成一個合法路徑已知一個陣列存放的是錄
名字,要求組合成一個合法路徑
比如:陣列中存放的是 home apple iOS
返回 /home/apple/iOS

    - (NSString *)joinPathOfComponents:(NSArray *)comp
    {
        NSMutableString * mstr = [[NSMutableString alloc]init];
        for (id obj in comp) {
            [mstr appendFormat:@"/%@",obj];
        }
        return mstr;
    }

7.用NSLog列印九九乘法表
- (void)print99Table
{
for(int i = 0 ; i < 10; i++)
{
for (int j = 0 ; j < 10 ; j++) {
NSLog(@"%d x %d = %d",i,j,i*j);
}
}
}

8.將C++的識別符號轉成OC的識別符號
C++的識別符號和OC一樣由數字字母下劃線組成,打頭的不是數字。當識別符號超過一個單詞,C++採用全字母小寫,單詞間用下劃線連線的書寫規範,如:apple_ios
OC採用除第一個單詞外,其餘單詞首字母大寫的書寫規範,如:appleios
傳入C++識別符號,返回OC識別符號

    - (NSString *)objcIdentifierFromCppIdentifier:(NSString *)idf
    {
        NSArray * arr = [idf componentsSeparatedByString:@"_"];
        NSMutableString * mstr = [[NSMutableString alloc]init];
        for (id obj in arr) {
            if ([arr indexOfObject:obj] != 0 ) {
                NSMutableString * tmstr = [NSMutableString stringWithString:obj];
                [tmstr replaceCharactersInRange:NSMakeRange(0, 1) withString:[NSString stringWithFormat:@"%c",[tmstr characterAtIndex:0]-32]];
                [mstr appendString:tmstr];
            }else
            {
                [mstr appendString:obj];
            }
        }
        return mstr;
    }

9、剔除字串中的全部空格
傳入: @"welcome to china”
返回:@"welcometochina”

 -(NSString *)stringWithoutSpaceInString:(NSString *)string
 {
     NSArray * arr = [string componentsSeparatedByString:@" "];
     NSMutableString * mstr = [[NSMutableString alloc]init];
     for (id obj in arr) {
         [mstr appendString:obj];
     }
     return mstr;
 }

10、計算兩個字串所表示數字的和
傳入:@"123" @"459"
返回:@"482"

-(NSString *)sumOfNumber:(NSString *)string1 andNumber:(NSString *)string2
{
    return [NSString stringWithFormat:@"%.0lf",[string1 doubleValue]+[string2 doubleValue]];
}

11.計算兩個字串所表示數字的乘積
傳入:@"15" @"15"
返回:@"255"

-(NSString *)productOfNumber:(NSString *)string1 andNumber:(NSString *)string2
{
    return [NSString stringWithFormat:@"%.0lf",[string1 doubleValue]*[string2 doubleValue]];
}

12、將字串後移
將字串向右移動指定位數,首尾迴圈
如:string傳入@ "welcometochina”, bits傳入5
返回:@“chinawelcometo”

-(NSString *)displacemetString:(NSString *)string forBits:(NSUInteger)bits
{
    NSMutableString * mstr = [[NSMutableString alloc]initWithString:string];
    NSString * str = [string substringFromIndex:[string length]-bits];
    [mstr replaceCharactersInRange:NSMakeRange(bits, [mstr length]-bits) withString:[mstr substringWithRange:NSMakeRange(0, [mstr length]-bits)]];
    [mstr replaceCharactersInRange:NSMakeRange(0, bits) withString:str];
    return mstr;
}

13、傳入兩個字串,找出第二個字串中每個字元在第一個字串中出現的次數
傳入:@"hello" @"abel"
返回:@"a:0 b:0 e:1 l:2"

- (NSString *)timesInString:(NSString *)str1 withCharactersInString:(NSString *)str2
{
    NSMutableString * mstr = [[NSMutableString alloc]init];
    for(int i = 0 ; i < [str2 length]; i++)
    {
        NSString * charStr = [str2 substringWithRange:NSMakeRange(i, 1)];
        NSArray * tarr = [str1 componentsSeparatedByString:charStr];
        [mstr appendFormat:@"%@:%lu ",charStr,[tarr count]-1];
    }
    return  mstr;
}

14.按照新規則比較兩個字串的大小
比較兩個字串的大小,首先比較兩個字串最後一個字元,如果最後一個字元相等,比較倒數第二個字元,如果字元相同,更長的大,依次類推,s1大返回1,s2大返回-1,相等返回0
傳入@"abc" @"abd" 返回-1
傳入@"abc" @"zabc" 返回-1
傳入@"abc" @"abc" 返回0

-(int)reverseWordsInString:(NSString *)str1 andOtherString:(NSString *)str2
{
    int length = (int)([str2 length]>[str1 length]?[str1 length]:[str2 length]);
    for (int i = length -1; i >= 0; i--) {
        if ([str1 characterAtIndex:i] > [str2 characterAtIndex:i]) {
        return 1;
        }else if([str1 characterAtIndex:i] < [str2 characterAtIndex:i]){
            return -1;
        }
    }
    return 0;
}

15.將字串中單詞按照出現次數排序,每個單詞只出現一次,源字串中單詞用下劃線連線,生成字串也應用下滑線連線
如傳入:@"good_good_study_good_study"
返回:@"good_study"

- (NSString *)sortStringByNumberOfWordsFromString:(NSString *)str
{
    NSArray * arr = [str componentsSeparatedByString:@"_"];
    NSMutableArray * tgtArr = [[NSMutableArray alloc]init];
    NSMutableDictionary * countDict = [[NSMutableDictionary alloc]init];
    int count = 0;
    for (id obj in arr) {
        if (![tgtArr containsObject:obj]) {
            [tgtArr addObject:obj];
        }
    }
    for (id obj in tgtArr) {
        for (id obj2 in arr) {
            if (obj == obj2) {
                count++;
            }
        }
        [countDict setObject:[[NSNumber alloc]initWithInt:count] forKey:obj];
        count = 0;
    }
    [tgtArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [countDict[obj1] intValue] <[countDict[obj2] intValue];
    }];
    return [tgtArr componentsJoinedByString:@"_"];
}

16.傳入兩個字串,第二個字串是一串連續數字,將第一個字串(不超過9個字元),按照第二個字串中所標示順序重新排序
傳入:@"abcdef" @"465231"
返回:@"dfebca”

-(NSString *)sortString:(NSString *)string asOrder:(NSString *)order
{
    NSMutableString * mstr = [[NSMutableString alloc]initWithString:string];
    NSMutableString * mstr2 = [[NSMutableString alloc]initWithString:order];

    for (int i = 0; i < [mstr length]; i++) {
        char c = [mstr characterAtIndex:i];
        for (int j = 0; j < [mstr2 length]; j++) {
            if ([mstr2 characterAtIndex:j] == i+49 ) {
                [mstr2 replaceCharactersInRange:NSMakeRange(j, 1) withString:[NSString stringWithFormat:@"%c",c]];
                break;
            }
        }
    }
    return mstr2;
}

文章優先發表於:http://keyliu.com
轉載請註明出處。

相關文章