java 如何从字符串中搜索特定字符并找出它出现的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13432890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 12:41:13  来源:igfitidea点击:

How to search a particular character from string and find how many times it occured

java

提问by user1832150

Store the following sentence in String

将以下句子存储在字符串中

“JAVA IS TOUGH LANGUAGE" 

I would like to ask a user to provide a character as an input and then print the total number of occurrence of that character in the above sentence. Moreover if a user wants to search a particular phrase or character in string he/she should able to search it.

我想请用户提供一个字符作为输入,然后打印上句中该字符出现的总数。此外,如果用户想要搜索字符串中的特定短语或字符,他/她应该能够搜索它。

Please tell me the simple way of beginners.

请告诉我初学者的简单方法。

回答by scanE

  String s ="JAVA IS TOUGH LANGUAGE";
       char c ='A'; //character c is static...can be modified to accept user input
    int cnt =0;
    for(int i=0;i<s.length();i++)
        if(s.charAt(i)==c)
            cnt++;
    System.out.println("No of Occurences of character "+c+"is"+cnt);

回答by Bohemian

The calculation can be done in one line:

计算可以在一行中完成:

String sentence ="JAVA IS TOUGH LANGUAGE";
String letter = "x"; // user input

int occurs = sentence.replaceAll("[^" + letter + "]", "").length();

This works by replacing every character that is notthe letter (using the regex [^x]) with a blank (effectively deleting it), then looking at the length of what's left.

这是通过将不是字母的每个字符(使用正则表达式[^x])替换为空白(有效地删除它),然后查看剩下的长度来工作的。

回答by Penelope The Duck

This version the user would pass in the character they wish to search for. So for example, from the command line they would call the program like so:

此版本用户将传入他们希望搜索的字符。例如,从命令行他们会像这样调用程序:

java TestClass A

This would search for "A" in the string.

这将在字符串中搜索“A”。

public class TestClass {
  static String searchString = "JAVA IS TOUGH LANGUAGE";
  static public void main(String[] args) {
    int answer = 0;
    if(args.length > 0){
        char searchChar = args[0].charAt(0);
        for (int i = 0; i < searchString.length(); i++){
            if (searchString.charAt(i) == searchChar){
                answer += 1;
            }
        }
    }
    System.out.println("Number of occurences of " + args[0] + " is " + answer);
  }
}