You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计字符串‘rajarajeshwari’中字母‘a’的出现次数

统计字符串rajarajeshwari中字母a的出现次数

Python 实现

最直接的方法是用字符串内置的count()方法:

s = 'rajarajeshwari'
a_count = s.count('a')
print(a_count)  # 输出: 5

如果需要手动遍历理解逻辑:

s = 'rajarajeshwari'
count = 0
for char in s:
    if char == 'a':
        count += 1
print(count)  # 输出: 5

JavaScript 实现

通过split()拆分后计算长度差:

const s = 'rajarajeshwari';
const aCount = s.split('a').length - 1;
console.log(aCount); // 输出: 5

手动遍历版本:

const s = 'rajarajeshwari';
let count = 0;
for (let char of s) {
    if (char === 'a') count++;
}
console.log(count); // 输出: 5

Java 实现

循环遍历字符数组:

public class CountChar {
    public static void main(String[] args) {
        String s = "rajarajeshwari";
        int count = 0;
        for (char c : s.toCharArray()) {
            if (c == 'a') {
                count++;
            }
        }
        System.out.println(count); // 输出: 5
    }
}

或者用Stream API简化:

import java.util.stream.IntStream;

public class CountChar {
    public static void main(String[] args) {
        String s = "rajarajeshwari";
        long count = s.chars().filter(c -> c == 'a').count();
        System.out.println(count); // 输出: 5
    }
}

内容的提问来源于stack exchange,提问作者Balaji Viswanathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:55:15