1. 程式人生 > 其它 >C++ 棧與堆詳談

C++ 棧與堆詳談

length屬性:字串的長度, 'abc'.length > 3

查詢方法

charAt():字串指定索引的字元,'abc'.charAt(1) > 'b', 'abc'.charAt(3) > '' 超出索引返回空串

 

indexOf(searchStr, [startIndex]),從startIndex的位置向後搜尋,沒有預設為0,返回字串開始的索引位置

lastIndexOf(searchStr, [endIndex]) 從endIndex的位置向後搜尋,沒有預設為length-1  'abcd'.lastIndexOf('bc',1) > 1
        從指定位置開始查詢,不遵循前閉後開原則

//查詢字串中所有的目標子串
function(str,findStr){
  let pos = str.indexOf(findStr)
  let positions = new Array()
  while(pos != -1){
      positions.push(pos)
      pos = str.indexOf(findStr,pos+1)            
  }          
  return position  
}

 

 

startsWith(str, [startIndex]): 是否以str在startIndex的位置開頭,沒有預設為0,返回布林值

endsWith(str, [lastIndex]): 是否以str在endIndex的位置結尾,,沒有預設為字串的結尾length,返回布林值

includes(str, [startIndex]):從startIndex開始是否包含str字串,返回布林值

        遵循前閉後開原則

 

字串的迭代器 let iterator = str[Symbol.iterator]()

迭代器訪問字串中的元素  iterator.next()  返回{value:xx,done:boolean}的物件

 

字串的操作

trim():清除字串兩端的空格  '  abc  '.trim() > 'abc'

trimLeft():清除字串左邊的空格  '  abc  '.trimLeft() > 'abc  '

trimRight():清除字串右邊的空格  '  abc  '.trimRight() > '  abc'

 

字串連線 concat()  可以有多個引數,效果和'+'相同, 'hello '.concat('world ','!','!') > hello world !!

字串的複製 repeat()    'hello'.repeat(2)+'!' > hellohello!

字串大小寫轉換:

toLowerCase():字串轉換成小寫 'Hello'.toLowerCase()  > hello

toUpperCase():字串轉換成大寫  'Hello'.toUpperCase() > HELLO

 

字串的擷取:

slice(startIndex,[endIndex]):入參擷取開始的索引,擷取結束的索引(沒有則為length),返回擷取後的字串,沒有返回空串.如果引數的索引為負取模,兩個引數需要按照大小順序傳遞

substring(startIndex,[endIndex]):入參擷取開始的索引,擷取結束的索引(沒有則為length),返回擷取後的字串,沒有返回空串.如果引數的索引為負取0,允許兩個引數不按大小順序傳遞

substr(startIndex,[length]):入參擷取開始的索引,第二個引數是要擷取的長度(沒有擷取到字串末尾,長度超過字串長度取字串長度),返回擷取後的字串,如果引數為負第一個引數取模,第二個引數取0

    遵循前閉後開原則

字串匹配

match():入參為字串或者正則表示式, 返回一個偽陣列物件,沒有匹配返回null  'hello'.match('o') > ['o',index:4,input:'hello',groups:undefined]  'hello'.match('i') > null

search():入參為字串後者正則表示式,返回index,沒有返回-1   'hello'.search(/o/) > 4     'hello'.search('i') > -1

replace():兩個引數第一個是字串後者正則表示式,第二是字串或者一個函式(使用函式可以對替換進行更精細的操作)   'hello'.replace('lo','id') > helid

//replace第二個引數是函式,將< > + 替換成轉義字元
function(str){
  return str.replace(/[<>"&]/g,function(match,pos,originalText){
       switch(match){
           case "<":
                return "&lt;"
           case ">":
                return "&gt;"
           case "&":
                return "&amp;"
           case "\"":
                return "&quot;"
        }        
    })  
}