string 常用方法

2022-07-04 08:45:12 字數 2092 閱讀 6358

/*

1、charat 和 charcodeat

charat方法和charcodeat方法都接收乙個引數,基於0的字元位置

charat方法是以單字元字串的形式返回給定位置的那個字元

charcodeat方法獲取到的不是字元而是字元編碼

*/var str = "hello world";

console.log(str.charat(1)); // e

console.log(str.charcodeat(1)); // 101

console.log(str[1]); // e

/* 2、concat */

var str = "hello ";

var res = str.concat("world");

console.log(res); // hello world

console.log(str); // hello

var res1 = str.concat("nihao","!");

console.log(res1); // hello nihao!

/* 3、

slice方法:第乙個引數指定子字串開始位置,第二個引數表示子字串最後乙個字元後面的位置

substring方法:第乙個引數指定子字串開始位置,第二個引數表示子字串最後乙個字元後面的位置

substr方法:第乙個引數指定子字串開始位置,第二個引數表示返回的字元個數

這三個方法都會返回被操作字串的乙個子字串,都接收一或兩個引數

如果沒有給這些方法傳遞第二個引數,則將字串的長度作為結束位置。這些方法也不會修改字串本身,只是返回乙個基本型別的字串值

*/var str = "hello world";

console.log(str.slice(3)); //lo world

console.log(str.substring(3)); //lo world

console.log(str.substr(3)); //lo world

console.log(str.slice(3,7)); //lo w 7表示子字串最後乙個字元後面的位置,簡單理解就是包含頭不包含尾

console.log(str.substring(3,7)); //lo w

console.log(str.substr(3,7)); //lo worl 7表示返回7個字元

console.log(str.slice(3,-4)); //lo w -4+11=7表示子字串最後乙個字元後面的位置 簡單理解就是包含頭不包含尾

console.log(str.substring(3,-4)); //hel 會轉換為console.log(str.substring(3,0));

console.log(str.substr(3,-4));

//此外由於這個方法會將較小數作為開始位置,較大數作為結束位置,所以相當於呼叫console.log(str.substring(0,3));

/* 4、

indexof方法和lastindexof方法都是從乙個字串中搜尋給定的子字串,然後返回子字串的位置,如果沒有找到,則返回-1

indexof方法是從字串的開頭向後搜尋子字串,lastindexof方法正好相反

這兩個方法都可以接收兩個引數:要查詢的子字串和查詢的位置

*/var str = "hello world";

console.log(str.indexof("o")); // 4

console.log(str.lastindexof("o")); // 7

console.log(str.indexof("o",6)); // 7

console.log(str.lastindexof("o",6)); // 4/* 5、trim方法用來刪除字串前後的空格 */

var str = " hello world ";

console.log('(' + str.trim() + ')');

console.log('(' + str + ')');

console.log(str.length);

String常用方法

1,startswith判斷是否以某字串開始 2,endswith判斷是否以某字串結尾 3,contains判斷是否包含另乙個字串 4,substring取出指定位置的字串 5,charat找到指定位置的字元 6,indexof正向找到指定字元的位置 7,lastindexof反向找到指定字元的位置...

string 常用方法

例項化方法建立字串 instancetype initwithstring nsstring astring instancetype initwithformat nsstring format,instancetype initwithutf8string const char bytes 類方...

String常用方法

public class teststring string str hello string的方法 1 跟字元陣列有關的方法 物件的長度 char array str.tochararray 把string物件轉換成char陣列 根據下標得到string物件該下標位置的字元 l 得到某個字元在st...