關於字串的相關操作

2021-06-29 06:06:07 字數 2523 閱讀 6181

//分割字串

nsstring *string = @"hello world";

nsarray *tmpary = [string componentsseparatedbystring:@" "];

nslog("%@",tmpary);

//字串替換

nsstring *string = @"hello world";

nsstring *newstring = [string stringbyreplacingoccurrencesofstring:@" " withstring:@","];

//查詢字串中是否含有某字元

nsstring *string = @"hello world";

nsstring *searchstring = @"hello";

if([string rangeofstring:searchstring].location != nsnotfound) else {

nslog(@"no");

//檢查字串是否以另乙個字串開頭或結尾

nsstring *string = @"hello world";

nsstring *searchstring = @"hello";

[string hasprefix:searchstring] == 1 ? nslog(@"yes") : nslog(@"no");

[string hassuffix:searchstring] == 1 ? nslog(@"yes") : nslog(@"no");

/*----------------抽取子串 ----------------*/

//-substringtoindex: 從字串的開頭一直擷取到指定的位置,但不包括該位置的字元

nsstring *string1 = @"this is a string";

nsstring *string2 = [string1 substringtoindex:3];

nslog(@"string2:%@",string2);

//-substringfromindex: 以指定位置開始(包括指定位置的字元),幷包括之後的全部字元

nsstring *string1 = @"this is a string";

nsstring *string2 = [string1 substringfromindex:3];

nslog(@"string2:%@",string2);

//-substringwithrange: //按照所給出的位置,長度,任意地從字串中擷取子串

nsstring *string1 = @"this is a string";

nsstring *string2 = [string1 substringwithrange:nsmakerange(0, 4)];

nslog(@"string2:%@",string2);

/*---------------在已有字串後面新增字元----------------*/

/*----------------改變字串的大小寫----------------*/

nsstring *string1 = @"a string";

nsstring *string2 = @"string";

nslog(@"string1:%@",[string1 uppercasestring]);//大寫

nslog(@"string2:%@",[string2 lowercasestring]);//小寫

nslog(@"string2:%@",[string2 capitalizedstring]);//首字母大小

//不考慮大小寫比較字串1

nsstring *astring01 = @"this is a string!";

nsstring *astring02 = @"this is a string!";

bool result = [astring01 caseinsensitivecompare:astring02] = = nsorderedsame;

nslog(@"result:%d",result);

//nsordereddescending判斷兩物件值的大小(按字母順序進行比較,astring02小於astring01為真)

//不考慮大小寫比較字串2

nsstring *astring01 = @"this is a string!";

nsstring *astring02 = @"this is a string!";

bool result = [astring01 compare:astring02

options:nscaseinsensitivesearch | nsnumericsearch] = = nsorderedsame;

nslog(@"result:%d",result);

//nscaseinsensitivesearch:不區分大小寫比較 nsliteralsearch:進行完全比較,區分大小寫 nsnumericsearch:比較字串的字元個數,而不是字元值。

關於字串相關操作

首先我們要建立乙個字串,並將字串複製給乙個變數。a i love you my lover a.find l start 0,end len a a.index l start 0,end len a 關於字串的切片操作。分為三個引數,開始 停止 步長。分別用冒號分割。例項 name jiangxi...

字串相關操作

注意 字串的操作 1 字串操作的時候 擷取的時候 他是包括前面 但是不包括後面。同時操作 字串的時候 他是從0位開始的,同時獲得字串的長度 是全部的長度 不是從0開始的。string str 6222370024642494 string str1 str.substring 0,6 string ...

字串的相關操作

str1 美麗的 str2 大好河山 res str1 str2 print res str1 重要的事情說三遍 res str1 3print res str1 sdfsdffsdfsfsfdfsdfsfdff 45245324534523 print str1 0 1 2 strvar 好天氣 ...