一、判斷字元串是否包含某個字元
我們在開發中,經常需要判斷一個字元串中是否包含某個字元。在Python中,可以使用in關鍵字來進行判斷。
string = "hello world" if "h" in string: print("包含h") else: print("不包含h")
正確輸出結果為:包含h
同樣的,在JavaScript中,可以使用indexOf方法進行判斷:
let string = "hello world"; if (string.indexOf("h") !== -1) { console.log("包含h"); } else { console.log("不包含h"); }
正確輸出結果為:包含h
不僅如此,在Java中可以使用contains方法進行判斷:
String string = "hello world"; if (string.contains("h")) { System.out.println("包含h"); } else { System.out.println("不包含h"); }
正確輸出結果為:包含h
二、查找字元串中所有某個字元出現的位置
有時候我們需要查找一個字元串中某個字元所有出現的位置,在Python中,可以使用findall方法:
import re string = "hello world" positions = [m.start() for m in re.finditer('l', string)] print(positions)
正確輸出結果為:[2, 3, 9]
,代表字元串中l出現的位置。
同樣的,在JavaScript中,可以使用正則表達式和match方法實現:
let string = "hello world"; let regex = /l/g; let positions = []; let match; while (match = regex.exec(string)) { positions.push(match.index); } console.log(positions);
正確輸出結果為:[2, 3, 9]
在Java中,可以使用indexOf方法和循環實現:
String string = "hello world"; int index = string.indexOf("l"); List positions = new ArrayList(); while (index >= 0) { positions.add(index); index = string.indexOf("l", index+1); } System.out.println(positions);
正確輸出結果為:[2, 3, 9]
三、替換字元串中的某個字元
有時候我們需要將字元串中某個字元全部替換成另一個字元,在Python中,可以使用replace方法實現:
string = "hello world" new_string = string.replace("l", "x") print(new_string)
正確輸出結果為:hexxo worxd
在JavaScript中,可以使用正則表達式和replace方法實現:
let string = "hello world"; let new_string = string.replace(/l/g, "x"); console.log(new_string);
正確輸出結果為:hexxo worxd
同樣的,在Java中,可以使用replace方法實現:
String string = "hello world"; String new_string = string.replace("l", "x"); System.out.println(new_string);
正確輸出結果為:hexxo worxd
四、統計字元串中某個字元出現的次數
有時候我們需要統計字元串中某個字元出現的次數,在Python中,可以使用count方法實現:
string = "hello world" count = string.count("l") print(count)
正確輸出結果為:3
在JavaScript中,可以使用正則表達式和match方法實現:
let string = "hello world"; let regex = /l/g; let match = string.match(regex); let count = match ? match.length : 0; console.log(count);
正確輸出結果為:3
同樣的,在Java中,可以使用循環和charAt方法實現:
String string = "hello world"; int count = 0; for (int i = 0; i < string.length(); i++) { if (string.charAt(i) == 'l') { count++; } } System.out.println(count);
正確輸出結果為:3
原創文章,作者:VVDDZ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/372930.html