2020-10-11

编写程序,统计出字符串“want you to know one thing ”中字母n和o的出现次数

一、简单的思路介绍

  1. 使用字符数组来存储字符串,使用for循环进行遍历,统计字符出现次数。
  2. 或者使用字符串,原先的字符串中对指定字母进行替换操作,产生新的字符串,比较二者的长度得出指定字母的出现次数。

二、一些String 类的操作方法的介绍

public char[] toCharArray()将一个字符串变为字符数组
public char charAt(int index)从一个字符串中取出指定位置的字符
public int length()去的字符串长度
public String replaceAll(String regex,String replacement)字符串替换
  1. 如何使用
    String str=“want you to know one thing”;
    char s[]=str.toCharArray();
    char ch=str.charAt(0)
    int i=str.length();
    String new_str=str.replaceAll(ch+"","");

三、代码

  1. 使用字符串
public class Homework5003 {
   public static void main(String[] args) {
       String str = "want you to know one thing";
       int count = 0;//统计单个字符出现的次数
       for (int i = 0; i < str.length(); i++) {
           int old_length = str.length();
           char ch = str.charAt(i);
           //定义一个字符等于字符串第一个字符.每次统计完会将统计过的字符替换掉.
           String new_str=str.replaceAll(ch+"","");//定义一个新字符串将出现的字符
           //赋给一个新的字符串
           int new_length=new_str.length();
           count = old_length - new_length;//旧的长度减去新的长度就是字符出现的 次数
           str=new_str;//将替换并统计过次数的字符串赋给原来的字符串,便于下一次遍历
  if(ch=='n'){
   System.out.println("字符" + ch + "出现了" + count + "次");
  }
  if(ch=='o'){
    System.out.println("字符" + ch + "出现了" + count + "次");
  }
 }
   }
}
  1. 使用字符数组
public class Homework500301 {
    public static void main(String[] args) {
        String str = "want you to know one thing";
  char s[]=str.toCharArray();
        int count = 0;//统计n字符出现的次数
  int c=0;//统计o字符出现的次数
        for (int i = 0; i < str.length(); i++) {
            if(s[i]=='n')
    count++;
   else if(s[i]=='o')
    c++;
   }
  System.out.println("n出现了"+count+"次"+'\n'+"o出现了"+c+"次");
  }
    }

第一次写博客,希望大佬们给些意见!
谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值