華為機試訓練2-計算字元個數
阿新 • • 發佈:2021-01-27
技術標籤:華為機試訓練演算法javascript前端node.js
華為機試訓練2-計算字元個數
題目描述
-
題目描述
- 寫出一個程式,接受一個由字母、數字和空格組成的字串,和一個字母,然後輸出輸入字串中該字母的出現次數。不區分大小寫。
-
輸入描述:
第一行輸入一個由字母和數字以及空格組成的字串,第二行輸入一個字母。
-
輸出描述:
輸出輸入字串中含有該字元的個數。
-
示例1
題目解析
- 這題也不難
- 首先,將字串(後文以
str
表示)和要計算的字元(後文以char
表示)全部轉小寫(或大寫),消除大小寫的影響 - 然後,宣告一個計數器
count
,記錄char
- 其次,迴圈遍歷
str
,將str
一個字元跟char
比較,相同則計數器加1 - 最後,返回計數器
count
程式碼
const readline = require('readline')
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
})
const inputArr = [] // 雖然題目沒有提,但是要考慮多組輸入的情況
rl.on('line', function (input) {
inputArr.push(input.trim()) // 消除頭尾空格的影響
})
// 統計字串 str 中 char 字母出現的次數
function countChars(str, char) {
// 統計的時候忽略大小寫
str = str.toLowerCase()
char = char.toLowerCase()
// 統計 char 出現的次數
let count = 0
// 遍歷字串
for(let i = 0; i < str.length; i++) {
if(str[i] === char) count ++
}
return count
}
rl.on('close', function () {
const res = [] // 儲存多組輸入的結果
for(let i = 0; i < inputArr.length; i+=2) {
let str = inputArr[i], // 輸入字串
char = inputArr[i+1] // 要統計的字母
let count = countChars(str, char)
res.push(count) // 儲存結果
}
// 多組輸出
res.forEach(output => console.log(output))
process.exit(0)
})