1. 程式人生 > >OC方法-- NSString擷取,比較,拼接,判斷,強轉

OC方法-- NSString擷取,比較,拼接,判斷,強轉

NSString:

1.subStringToIndex:1  擷取字串,(擷取到1)

  NSString *str = @"我是一串字串";
    NSString *strJieQu = [str substringToIndex:1];
    NSLog(@"擷取str:%@", strJieQu);
 執行結果:擷取str:我

2.subStringFromIndex:1 擷取字串(從1開始擷取)

NSString *str = @"我是一串字串";
    NSString *strJieQu = [str substringFromIndex:1];
    NSLog(@"擷取str:%@", strJieQu);
執行結果:擷取str:是一串字串

3. stringWithFormat:(NSString) 字串的萬能初始化方法

 NSString *str = @"我是一串字串";
    NSInteger num = 5;
    CGFloat floatNum = 3.14;
    NSString *strJieQu = [NSString stringWithFormat:@"%@, %ld, %f", str, num, floatNum];
    NSLog(@"擷取str:%@", strJieQu);

執行結果:我是一串字串, 5, 3.140000

4.stringByReplaceOccurrencesOfString:(NSString) withString:(NSString)字串的替換

    NSString *str = @"我是一串字串";
    NSString *strJieQu = [str stringByReplacingOccurrencesOfString:@"我" withString:@"你"];
    NSLog(@"擷取str:%@", strJieQu);
執行結果:擷取str:你是一串字串

5.stringByAppendingFormat:(NSString) 字串的拼接

    NSString *str = @"我是一串字串";
    NSString *strJieQu = [str stringByAppendingFormat:@"%@, 我很happy", str];
    NSLog(@"擷取str:%@", strJieQu);
執行結果:擷取str:我是一串字串我是一串字串, 我很happy

6. 判斷字串是否相等:
     isEqual:
     isEqualToString:(NSString);

   常用於if條件判斷

NSString *str = @"我是一串字串";
    NSString *strJieQu = [str stringByAppendingFormat:@"%@, 我很happy", str];
    if ([str isEqualToString:@"我是一串字串"]) {
        
        NSLog(@"一樣");
    }
    else
    {
        NSLog(@"擷取str:%@", strJieQu);
    }
執行結果:一樣

7. compare : 字串比較

    NSString *str = @"我是一串字串";
    NSLog(@"擷取str:%ld", (long)[str compare:@"178"]);
執行結果:1

8. hasPrefix: 判斷字串開頭是否相等

    NSString *str = @"我是一串字串";
    if ([str hasPrefix:@"我"]) {
        
        NSLog(@"YES");
    }
    else
    {
        NSLog(@"NO");
    }
執行結果:YES

9. hasSuffix: 判斷字串結尾是否相等

    NSString *str = @"我是一串字串";
    if ([str hasSuffix:@"我"]) {
        
        NSLog(@"YES");
    }
    else
    {
        NSLog(@"NO");
    }
執行結果:NO 10. intValue   :強轉成整型
11.integerValue :強轉成NSInteger型

12 floatValue:強轉CGFloat型