一些方法需要指定乙個範圍確定字串,包括開始索引數和字元數,索引數以0開始。在foundation的框架中的一些方法,使用了特殊的資料型別nsrange建立範圍物件。實際上,它是結構typedef定義,包含location和length兩個成員。
現在有如下**:
#import
int main ()
else
nslog
(@"string is at index %lu,length is %lu",subrange.
location
,subrange.
length);
}return0;}
執行結果:
2014-08-24 10:40:15.737 testoc[622:303] first 3 chars of str1:thi
2014-08-24 10:40:15.739 testoc[622:303] chars from index 8 through 13:is string a
2014-08-24 10:40:15.739 testoc[622:303] chars from index 8 through 13:string
2014-08-24 10:40:15.740 testoc[622:303] chars from index 8 through 13:string
2014-08-24 10:40:15.740 testoc[622:303] string is at index 8,length is 8
2014-08-24 10:40:15.741 testoc[622:303] string not found
program ended with exit code: 0
substringtoindex:方法建立了乙個子字串,包含首字元到指定的索引數,但不包括該索引值對應的字元。對於所有採用索引數作為引數的字串方法,如果提供的索引數對改字元無效,就會獲得range or index out of bounds的出錯訊息。
substringfromindex: 方法返回了乙個子字串,它從接受者指定的索引字元開始,直到字串的結尾。
使用substringwithrange:方法能夠一步完成我們剛剛用substringtoindex:和substringfromindex: 兩步所做的工作,接受乙個範圍。返回指定範圍的字元。特殊函式
nsmakerange (8,6)
根據引數建立乙個範圍,並返回結果。這個結果可以作為substringwithrange:方法的引數。
要在另乙個字串中查詢乙個字串,可以使用rangeofstring:方法。如果在接收者中找到指定的字串,則返回的範圍是找到的精確的位置。然而,如果沒有找到字串,則返回的location成員被設定為nsnotfound。例如:
subrange = [str1 rangeofstring: @"string a"];
把方法返回的nsrange結構賦值給nsrange變數subrange。一定要要注意。subrange不是物件變數,而是乙個結構變數(並且程式中的subrange宣告不包括星號,這通常意味著不是在處理乙個物件,不過id型別是個例外)。
字串物件python int 字串 字串物件
最近研究字串物件,稍微總結一下,以後繼續補充 如果我們須要把python的字串物件轉換為數整物件,我們須要用到int方法。比如 ainfo 222 print int ainfo 輸出的結果是222。然後我們檢視下ainfo在現的型別,通過type方法檢視下,發現是 而如果ainfo fefew22...
字串物件
對一直字串進行操作 var str life is a foreign language all men mispronounce it 測試長度 str.length 為字串新增樣式 var txt hello world document.write big txt.big document.w...
字串物件
常用的定義字串物件的方法是 string int 當同乙個物件需進行多次定義的時候,除了第一次,剩下的可直接定義 例如 int i 1 第二次 i 2 public int indexof 是尋找所需內容第一次出現的位置 public int lastindexof 是尋找所需內容最後一次出現的位置...