我希望使用JavaScript计算给定字符串中每个字符出现的次数。
例如:
var str = "I want to count the number of occurrences of each char in this string";
输出结果应为:
h = 4;
e = 4; // and so on
我尝试在 Google 上搜索,但没有找到答案。我想要实现类似这个的功能;顺序不重要。
我希望使用JavaScript计算给定字符串中每个字符出现的次数。
例如:
var str = "I want to count the number of occurrences of each char in this string";
输出结果应为:
h = 4;
e = 4; // and so on
我尝试在 Google 上搜索,但没有找到答案。我想要实现类似这个的功能;顺序不重要。
您可以使用对象来完成任务。
步骤1 - 创建一个对象
步骤2 - 遍历字符串
步骤3 - 将字符作为键,字符计数作为值添加到对象中
var obj={}
function countWord(arr)
{
for(let i=0;i<arr.length;i++)
{
if(obj[arr[i]]) //check if character is present in the obj as key
{
obj[arr[i]]=obj[arr[i]]+1; //if yes then update its value
}
else
{
obj[arr[i]]=1; //initialise it with a value 1
}
}
}
function getNoOfOccurences(str){
var temp = {};
for(var oindex=0;oindex<str.length;oindex++){
if(typeof temp[str.charAt(oindex)] == 'undefined'){
temp[str.charAt(oindex)] = 1;
}else{
temp[str.charAt(oindex)] = temp[str.charAt(oindex)]+1;
}
}
return temp;
}
我尝试使用“空格”和“特殊字符”进行检查:
function charCount(str){
const requiredString = str.toLowerCase();
const leng = str.length;
let output = {};
for(let i=0; i<leng; i++){
const activeCharacter = requiredString[i];
if(/[a-z0-9]/.test(activeCharacter)){
output.hasOwnProperty(activeCharacter) ? output[activeCharacter]++ : output[activeCharacter] = 1;
}
}
return output;
}
let newStr= "asafasdhfasjkhfweoiuriujasfaksldjhalsjkhfjlkqaofadsfasasdfas";
function checkStringOccurnace(newStr){
let finalStr = {};
let checkArr = [];
let counterArr = [];
for(let i = 0; i < newStr.length; i++){
if(checkArr.indexOf(newStr[i]) == -1){
checkArr.push(newStr[i])
let counter = 0;
counterArr.push(counter + 1)
finalStr[newStr[i]] = 1;
}else if(checkArr.indexOf(newStr[i]) > -1){
let index = checkArr.indexOf(newStr[i])
counterArr[index] = counterArr[index] + 1;
finalStr[checkArr[index]] = counterArr[index];
}
}
return finalStr;
}
let demo = checkStringOccurnace(newStr);
console.log(" finalStr >> ", demo);
package com.company;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// write your code here
HashMap<Character, Integer> sHashMap = new HashMap(); // using hashMap<key , value > here key = character and value = count
String arr = "HelloWorld";
for (int i = 0; i < arr.length(); i++) {
boolean flag = sHashMap.containsKey(arr.charAt(i)); // check if char is already present
if (flag == true)
{
int Count = sHashMap.get(arr.charAt(i)); // get the char count
sHashMap.put(arr.charAt(i), ++Count); // increment the count and update in hashMap
}
else
{
sHashMap.put(arr.charAt(i), 1); //if char not present then insert into hashMap
}
}
System.out.println(sHashMap);
//OutPut would be like ths {r=1, d=1, e=1, W=1, H=1, l=3, o=2}
}
}
// Converts String To Array
var SampleString= Array.from("saleem");
// return Distinct count as a object
var allcount = _.countBy(SampleString, function (num) {
return num;
});
// Iterating over object and printing key and value
_.map(allcount, function(cnt,key){
console.log(key +":"+cnt);
});
// Printing Object
console.log(allcount);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<p>Set the variable to different value and then try...</p>
function cauta() {
var str = document.form.stringul.value;
str = str.toLowerCase();
var tablou = [];
k = 0;
//cautarea caracterelor unice
for (var i = 0, n = 0; i < str.length; i++) {
for (var j = 0; j < tablou.length; j++) {
if (tablou[j] == str[i]) k = 1;
}
if (k != 1) {
if (str[i] != ' ')
tablou[n] = str[i]; n++;
}
k = 0;
}
//numararea aparitilor
count = 0;
for (var i = 0; i < tablou.length; i++) {
if(tablou[i]!=null){
char = tablou[i];
pos = str.indexOf(char);
while (pos > -1) {
++count;
pos = str.indexOf(char, ++pos);
}
document.getElementById("rezultat").innerHTML += tablou[i] + ":" + count + '\n';
count = 0;
}
}
}
let str = "aabbcc"
let obj = {}
for (let item of str) {
if (!obj[item]) {
obj[item] = 1
} else {
obj[item] = obj[item] + 1
}
}
console.log(obj)
试一下
let txt = 'hello';
let txtArr = txt.split('');
let objCnt = txtArr.reduce((accum, currVal) => {
accum[currVal] = (accum[currVal] || 0) + 1;
return accum;
}, {});
console.log(objCnt);
我认为最少的代码行是最好的解决方案。就像这样。
let text= 'I want to count the number of occurrences of each char in this string';
const obj = {};
for (let i = 0; i < text.length; i++) {
const ele = text[i];
obj[ele] === undefined ? obj[ele] = 1 : obj[ele]++
}
console.log(obj);
第二个例子。
text.split('').forEach((ele) => {
obj[ele] === undefined ? obj[ele] =1 : obj[ele]++
})
console.log(obj);