字串函式

2021-10-25 09:11:18 字數 3149 閱讀 5895

var str =

"aheloworld"

;

var str =

"aheloworld"

;console.

log(

"str變數中字串的長度為:"

+str.length)

可以通過下標的方式獲取字串中的值,但是不能進行更改

var str =

"aheloworld"

;var str1 = str.

charat(3

)console.

log(

"通過charat()方法指定下標返回字元為:"

+str1)

可返回指定位置的字元的 unicode 編碼 語法string.charcodeat(index)

var str =

"aheloworld"

;var str1 = str.

charcodeat(0

)console.

log(

"通過charcodeat()方法指定下標返回指定位置的字元的 unicode 編碼為:"

+str1)

可接受乙個指定的 unicode 值,然後返回乙個字串

var str1 = string.

fromcharcode(65

)console.

log(

"fromcharcode()指定的 unicode 值,然後返回乙個字串"

+str1)

拼接字串 可同時拼接過個字串 作用等同於+

var str1 = str.

concat

("二傻子"

,"三傻子"

)console.

log(

"concat() 拼接字串後的結果為:"

+str1)

可返回某個指定的字串值在字串中首次出現的位置。如果沒有找到匹配的字串則返回 -1

var str3 =

"heloworld"

var str1 = str3.

indexof

("l");

console.

log(

"通過indexof()查詢指定字串第一次出現的位置的下標:"

+str1)

//2var str1 = str3.

indexof

("l",3

);console.

log(

"通過indexof()查詢指定字串規定字串查詢位置的開始地點,返回出現的位置的下標:"

+str1)

var str1 = str3.

indexof

("l");

console.

log(

"通過indexof()查詢指定字串如果字串不存在,返回-1:"

+str1)

從後往前找,下標從0往後數

var str2 =

"abcabcabc"

var str1 = str2.

lastindexof

("a"

)console.

log(

"通過lastindexof()查詢指定字串最後一次出現的位置的下標【從後往前找,下標從0往後數】:"

+str1)

方法可提取字串的某個部分,並以新的字串返回被提取的部分。 不改變源陣列

/* 

引數1:開始位置的索引(包含了開始位置)

引數2:結束位置的索引(不包含結束位置)

注意:1- 如果省略第二個引數,則會擷取後面所有的字串

2- 如果傳遞乙個負數,會從後面開始計算

*/var str2 =

"abcabcabc"

var str1 = str2.

slice(1

,4) console.

log(

"slice()方法提取str2字串中 下標1開始到下標4之前結束的字串為:"

+str1)

var str1 = str2.

slice(1

,-3)

// bcabc

var str1 = str2.

slice(0

)//bcabcabc

var str1 = str2.

slice(-

3,-1

)//ab

console.

log(str1)

可在字串中抽取從 開始 下標開始的指定數目的字元。

引數1:提取字串的起始位置 如果為負數,預設從後向前計算

引數2:提取字串的數量

注意:無論是正數還是負數 都從左向右計算

var str2 =

"abcabcabc"

var str1 = str5.

substr(2

,3)var str1 = str5.

substr(-

3,3)

console.

log(str1)

用於把乙個字串分割成字串陣列。

如果不指定拆分的字元,則每個字元為乙個陣列元素

如果指定拆分的字元,則以指定字元拆分為陣列元素

var str2 =

"guoxiaoyang"

var arr = str5.

split(""

)var arr = str5.

split

("o"

)console.

log(arr)

var str6 =

"abcabc"

console.

log(

"轉為大寫"

+str6.

touppercase()

)console.

log(

"轉為小寫"

+str6.

tolowercase()

)

字串和字串函式

字元輸入輸出 getchar putchar ch getchar putchar ch 字串函式 字串輸入 建立儲存空間 接受字串輸入首先需要建立乙個空間來存放輸入的字串。char name scanf s name 上述的用法可能會導致程式異常終止。使用字串陣列 可以避免上述問題 char na...

字串和字串函式

1.字串字面量 字串常量 用雙引號括起來的內容稱為字串字面量,也叫字串常量。字串常量屬於靜態儲存類別,這說明如果在函式中使用字串常量,該字串只會被儲存一次,在整個程式的生命期內存在,計時函式被呼叫多次。用雙引號括起來的內容被視為指向該字串儲存位置的指標。hello 中的 hello 類似於乙個陣列名...

字串函式

1 獲取字串的長度 length 2 判斷字串的字首或字尾與已知字串是否相同 字首 startswith string s 字尾 endswith string s 3 比較兩個字串 equals string s 4 把字串轉化為相應的數值 int型 integer.parseint 字串 lon...