Objective-C之Foundation中的NSString的一些常用的方法

來源:互聯網
上載者:User

[str hasPrefix:@"12"]; //以12開頭 傳回值Bool
[str hasSuffix:@"txt"]; //是否以txt結尾 返回Bool

//搜尋字串
[str rangeOfString:@"345"]; //返回位置 返回NSRange如果找不到返回{NSNotFound,0}
//從尾部搜尋
NSRange range = [str rangeOfString:@"456" options:NSBackkwardsSearch];

#pragma mark 字串截取
NSString *str = @"123456";
//從索引3開始截取到尾部
NSLog( @"%@",[str substringFromIndex:3] ); //列印456
//從頭部開始截取到索引3之前(不包括3)
NSLog(@"%@", [str substringToIndex:3]); //列印123
//指定範圍進行截取
NSRange range = NSMakeRange(2, 3);
NSLog(@"%@",[str substringWithRange:range]); //列印345

NSString *str2 = @"1,2,3,4,5";
//用逗號分隔
NSArray *array = [str2 componentsSeparateByStirng:@","];
NSLog(@"%@", array);

NSString *str3 = [array objectAtIndex:0];
NSLog(@"%@",str3); //列印 1

NSString與路徑:

#pragma mark
NSArray *components = [NSMutableArray array]; //NSMutableArray可變的
[components addObject:@"Users"];
[components addObject:@"gongpb"];
[components addObject:@"Desktop"];
//將數組中的所有字串拼接成一個路徑
NSString *path = [NSString pathWithCompoents:components]; //列印 Users/gongpb/Desktop
NSLog(@"%@", path);

NSArray *cmps = [path pathComponents]; //分解
NSLog(@"%@", cmps); //(Users, gongpb,Desktop)

path = @"Users/gongpb/Desktop/test";
NSLog(@"%i", [path isAbsolutePath]); //返回0 就是判斷依據是 最前邊是否有斜杠/
//最後一個檔案夾
NSLog(@"最後一個目錄:%@",[path lastPathComponent]); //返回 test

//刪除最後一個檔案夾
NSLog(@"%@",[path stringByDeletingLastPathComponent] ); 返回Users/gongpb/Desktop 刪除了/test

//在最後拼接一惡搞目錄
NSLog(@"%@", [path stringByAppendingPathComponent:@"abc"]); //返回/Users/gongpb/Desktop/test/abc

NSString *str = @"/User/gongpb/test.txt";
NSLog(@"%@", [str pathExtension]); //擷取副檔名,
//刪除副檔名
[str stringByDeletingPathExtension];
//添加副檔名
[@"abc" stringByAppendingPathExtension:@"mp3"];

其它用法:
NSString *str=@"12";
int a = [str intValue]; //轉int

//計算字數,不是計算字元數
[str length];

//擷取字元
unichar c = [@"abc" characterAtIndex:0];
NSLog(@"%c", c);

//返回C語言中的字串 const:表明s是常量
const char *s = [@"abc", UTF8String];
NSLog(@"%s", s);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.