輸入字符串中含有該字符的個數

##需求:寫出一個程序,接受一個有字母和數字以及空格組成的字符串,和一個字符,而後輸出輸入字符串中含有該字符的個數。不區分大小寫。 ##Input:java

  • 字符串(字母、數字、空格)code

  • 字符 ##Output:字符串

  • 字符個數input

##代碼實現:class

import java.util.Scanner;
public class Main{
    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        String str=input.nextLine();
        String chara=input.next();
        int num=0;
        for(int i=0;i<str.length();i++){
            if(chara.equalsIgnoreCase(String.valueOf(str.charAt(i))))
                num++;
        }
        System.out.println(num);
        input.close();
    }
}

###解決問題的要點在於:import

##區分大小寫比較字符串的時候,要使用String的valueOf方法對char類型的數據進行類型轉換,而後再使用String類的equalsIgnoreCase方法進行比較.程序

相關文章
相關標籤/搜索