简体   繁体   English

使用Java的字符串中的字符的次数?

[英]Number of Times a Character in String using java?

I searched for method to calculate how many times a character is in String and found a good solution 我搜索了一种方法来计算一个字符在String中的次数,并找到了一个好的解决方案

temp.length() - temp.replaceAll("T", "").length()

here,we are calculating the number of time 'T' is in temp... 在这里,我们正在计算时间“ T”处于临时状态的时间...

Problem is,it is not working properly for '.' 问题是,它无法正常运行。

Code: 码:

public static void main(String[] args) {
    String temp="TTT..####";
    System.out.println(temp.length() - temp.replaceAll("T", "").length());
    System.out.println(temp.length() - temp.replaceAll(".", "").length());
    System.out.println(temp.length() - temp.replaceAll("#", "").length());
}

OutPut: 输出:

run:
3
9
4
BUILD SUCCESSFUL (total time: 1 second)

according to output '.' 根据输出“。” is 9 times in String.through loop it's gives the right answer. 在String.through循环中是9次,它给出了正确的答案。 What is the problem?? 问题是什么??

Use replaceAll("\\\\.", "").length()); 使用replaceAll("\\\\.", "").length());

replaceAll() takes a REGEX as input. replaceAll()REGEX作为输入。 . has a special meaning in REGEX, it means any character . 在REGEX中有特殊含义,表示任何字符 You need to escape it by using 2 \\\\ s 您需要使用2 \\\\ s对其进行转义

EDIT: 编辑:

Use : 采用 :

String temp = "TTT..####";
System.out.println(temp.split("\\.", -1).length - 1);

// using -1 as limit in split() divides the String based on the passed argument (and gives empty Strings as result, if needed). //使用-1作为split() 限制 ,可根据传递的参数对String进行split()并在需要时给出空字符串作为结果)。 So, in the split array you will have n+1 elements, where n is the number of occurances of the particular argument. 因此,在拆分数组中,您将具有n+1元素,其中n是特定参数的出现次数。 So, we are doing length-1 . 因此,我们正在执行length-1

replaceAll() takes a regex and . replaceAll()使用正则表达式和. mathces any char . 计算任何char This is the reason why your output is 9 in this case 这就是在这种情况下您的输出为9的原因

You can find the number of times for every character in one iteration like this 您可以像这样在一次迭代中找到每个字符的次数

Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i < temp.length(); i++)
{
    char c = temp.charAt(i);
    if(!map.containsKey(c))
    {
        map.put(c, 1);
    }
    else
    {
        map.put(c, map.get(c)+1);
    }
}
for(Character c : map.keySet())
{
    System.out.println("" + c + " : " + map.get(c));
}

People have already answered that you need to use \\\\. 人们已经回答您需要使用\\\\. instead of . 代替. in the regex. 在正则表达式中。 I just figured this could be a slightly more general solution for this particular problem with some minor alteration. 我只是认为这可以通过一些较小的改动来解决此特定问题,但它可能是稍微更通用的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM