iOS開發中對OC字串的相關操作《轉》

2021-07-05 12:37:43 字數 1637 閱讀 3178

oc中對字串進行操作使用了foundation框架中的nsstring類(不可變)、nsmutablestring類(可變)。

nsstring

1、建立字串

[objc] view plaincopy

nsstring *str1 = @"我在學習oc";  

nsstring *str2 = [[nsstring alloc] initwithstring: @"我在學習oc"];  

nsstring *str3 = [nsstring stringwithformat: @"我在學習%@",@"oc"];  

nsstring *str4 = [[nsstring alloc] initwithutf8string:"我在學習oc"];    // 由c字串轉換成oc字串  

2、獲取字串長度

[objc] view plaincopy

nsuinteger length = str.length;  

3、獲取字串某個位置的字元

[objc] view plaincopy

unichar c = [str characteratindex:1]; // 索引從0開始  

4、擷取字串

[objc] view plaincopy

nsrang *rang = ; //location(索引開始的位置)、length(擷取的長度);  

nsstring *substring = [str substringwithrange:rang];  

5、獲取子字串在字串中的索引位置和長度

[objc] view plaincopy

nsrange range = [str rangeofstring:substring]; // 如果未找到 返回  

6、判斷字串內容是否相同

[objc] view plaincopy

bool isequal = [str1 isequaltostring:str2]  

7、替換字串中的子字串為給定的字串

[objc] view plaincopy

nsstring * newstr = [str stringbyreplacingoccurrencesofstring: @"a" withstring: @"b"];  

nsmutableablestring

1、追加字串返回新字串

[objc] view plaincopy

nsstring *str = it  

2、追加字串

[objc] view plaincopy

nsmutableablestring *mstr = [[nsmutableablestring alloc] init];  

3、在指定的索引位置插入字串

[objc] view plaincopy

[mstr insertstring: @「itheima」 atindex:2];  

4、刪除指定範圍的字串

[objc] view plaincopy

nsrange range = ;  

[mstr deletecharactersinrange:rang];  

oc中的字串常用方法 (出處: 黑馬程式設計師it技術論壇)

iOS中OC載入HTML字串

最近專案裡面遇見了 html 字串,整理如下 後台返回字串的樣式 在 ios 中通常載入 html 字串有兩種方式 void viewdidload 將 等類似的字元轉化為html中的 nsstring htmlentitydecode nsstring string 將html字串轉化為nsatt...

OC中字串用法總結

注 nsstring不可變字串 1.通過字面量方式建立乙個字串 nsstring str 字串 2.輸出字串長度length nslog ld str.length 3.通過指定下標獲取字元內容 列印漢字時c要大寫 nslog c str characteratindex 下標數 4.系統提供的便利...

OC中字串的簡單操作

import int main int argc,const char argv else 6.字串擷取 6.1 擷取前面部分 nslog str1 substringfromindex 3 6.2 擷取後邊部分 nslog str1 substringtoindex 3 6.3 擷取中間部分 ns...