創建一個字符串對象:
NSstring * str1 = @"hello world";
NSString * str = [[NSString alloc]initWithString:@"hello world!"];
NSString * str_1 = [[NSString alloc]initWithUTF8String:"hello world"];//把C的字符串轉化為OC的字符串
int a = 123;
NSString * str_3 = [[NSString alloc]initWithFormat:@"a = %d %s%@", a, "abcd", @"efg"];//用格式化字符串初始化
//可完成字符串的拼接以及完成C的字符串與OC的字符串的轉化
NSString * str1 = [NSString stringWithString:@"hello world"];
NSString * str2 = [NSString stringWithUTF8String:"hello world"];
NSString * str3 = [NSString stringWithFormat:@"%s","hello world"];
NSstring * str1 = @"hello";
NSString * str = [[NSString alloc]initWithString:@"hello world!"];
NSString * str_1 = [[NSString alloc]initWithUTF8String:"hello world"];//把C的字符串轉化為OC的字符串
int a = 123;
NSString * str_3 = [[NSString alloc]initWithFormat:@"a = %d %s%@", a, "abcd", @"efg"];//用格式化字符串初始化
字符串轉化:
NSString * str = @"hello";
const char *p = [str UTF8String];將OC字符串轉化為C的字符串
str = @"123";
int a = [str intValue];//將數字串轉化成整型數據
[str floatValue];//將數字串轉化成float型
[str doubleValue];//將數字串轉化成double型
NSString * str = @"hello";
const char *p = [str UTF8String];將OC字符串轉化為C的字符串
str = @"123";
int a = [str intValue];//將數字串轉化成整型數據
[str floatValue];//將數字串轉化成float型
[str doubleValue];//將數字串轉化成double型
常用的NSString :
NSLog(@"%ld",[str1 length]); //求字符串長度
NSLog(@"%c", [str1 characterAtIndex:1]);//獲取字符串中的字符
BOOL ret = [str1 isEqualTo:str2];//比較兩個字符串是否相等,相等返回YES(1),不相等返回NO(0) (BOOL YES(1) NO(0))
long ret1 = [str1 compare:str2];//比較兩個字符串的大小,str1大於 返回1 相等返回0 小於返回-1
long ret2 = [str1 caseInsensitiveCompare:str2];//不區分大小寫比較字符串大小
NSString * ptr = [str2 uppercaseString];//將字符串中的所有小寫字符轉換成大寫 不改變原來的字符串
ptr = [str1 lowercaseString];//將字符串中的所有大寫字符轉換成小寫 不改變原來的字符串
ptr = [str3 capitalizedString];//將字符串中出現的第一個字母轉換成大寫,其余字母小寫
NSString * str4 = @"hello world";
NSRange range = [str4 rangeOfString:@"wr"];//查找子串,找不到返回NSNotFound 找到返回location和length
if (range.location != NSNotFound) {
NSLog(@"%ld %ld",range.location, range.length);
}
NSString * str5 = @"helloworld";
NSString * ptr1 = [str5 substringToIndex:4];//字符串抽取 從下標0開始到4 不包括4
NSString * ptr2 = [str5 substringFromIndex:5];//從下標5開始抽取到字符串結束 包括5
NSRange range1 = {4,3};//結構體初始化
NSString * ptr3 = [str5 substringWithRange:range1];//在range指定范圍內抽取
NSString * ptr4 = [str5 substringWithRange:NSMakeRange(4,3)];//NSMakeRange可以生成一個結構體
NSString * str = @"www.baidu.com";
BOOL ret = [str hasPrefix:@"www"];//判斷字符串是否以指定字符串開頭
NSString * str1 = @"1.txt";
BOOL ret1 = [str hasSuffix:@".txt"];//判斷字符串是否以指定的字符串結尾
NSMutableString可變字符串(動態增加和減少的) 繼承於NSString可以使用NSString的所有方法
NSMutableString * str = [[NSMutableString alloc]initWithString:@"hello"];//將不可變的字符串轉換為可變的字符串
[str insertString:@"123" atIndex:1];//在指定下標(不要越界)位置插入NSString類型字符串
[str appendString:@"123"];//在字符串末尾追加字符串
[str deleteCharactersInRange:NSMakeRange(0, 2)];//從指定下標刪除length個字符
[str setString:@"baidu"];//修改字符串亦稱對該可變字符串賦值
[str replaceCharactersInRange:NSMakeRange(3, 1) withString:@"ios"];//將指定下標位置的length個字符替換為指定的字符串