Java 查找字符串中的重复字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18289325/
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-08-12 00:05:39  来源:igfitidea点击:

Finding a repeated character in a string

javastringcharacterrepeat

提问by Luis Lainez

The problem states the following: given a string and a character by the user find the number of times the character (given by the user) repeats itself in the string (also given by the user).

问题说明如下:给定一个字符串和用户指定的字符,找出该字符(由用户提供)在字符串(也由用户提供)中重复的次数。

I have this piece of code

我有这段代码

public int repeticion (int s){
        int return = 0;
        int cont = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Write a string: ");
        String chain = in.next();
        System.out.println("Write the character: ");
        String character = in.next();
        if (chain.contains(character)) {
            cont = cont + 1;
        }
        System.out.println("The character repeats itself "+cont+"times");
        return return;

But as you can see the .containsonly counts the character once, not the number of times it appears in the string.

但是正如您所看到的,.contains只计算字符一次,而不是它在字符串中出现的次数。

回答by Brandon McKenzie

Contains will simply tell you if the character is present. To actually count the number of times that character would appear, you'll need to iterate over the string and count the number of times the selected character appears. This method will work:

包含只会告诉您该角色是否存在。要实际计算该字符出现的次数,您需要遍历字符串并计算所选字符出现的次数。此方法将起作用:

public countACharacter(char thecharacter, String stringtocountcharactersin) {
    int count = 0;
    for(int i = 0; i < stringtocountcharactersin.length(); i++) {
        if(stringtocountcharactersin.charAt(i) == thecharacter) {
            count++;
        }
    }
    return count;
}

回答by nullpointr

.contains()only says that a character exists within a string, not how many. You need to iterate over each character of a string to check if it equals the character you are searching for.

.contains()只表示字符串中存在一个字符,而不是多少。您需要遍历字符串的每个字符以检查它是否等于您要搜索的字符。

String chain = "your string";
int cont = 0;
for(int i=0; i<chain.length(); i++) {
   if(chain.charAt(i) == character) {
      cont++;
   } 
}

回答by Moogle

You could also repeatedly check that the character is in the string, get that index, then check the substring from after that index to the end of the string. I recommend the following:

您还可以反复检查字符是否在字符串中,获取该索引,然后检查从该索引之后到字符串末尾的子字符串。我推荐以下内容:

int index = 0;
int count = 0;
while (chain.indexof(character, index) != -1  && index < chain.length()-1) {
    index = chain.indexof(character, index) + 1;
    count++;
}

回答by Raj008

//With out string methods. public static void main(String[] args) {

//没有字符串方法。公共静态无效主(字符串 [] args){

    String ss="rajesh kumar";

    Field value = null;
    try {
        value = String.class.getDeclaredField("value");
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // It's private so we need to explicitly make it accessible.

    value.setAccessible(true);

    try {
        char[] values = (char[])value.get(ss);

        //String is converted to char array with out string functions

        for (int i = 0; i < values.length; i++) {

            int count=0;
            for(int j=0;j<values.length;j++)
            {
                if(values[i]== values[j])
                {
                    count++;
                }
            }
            System.out.println("\n Count of :"+values[i] +"="+count);

        }

        System.out.println("Values "+values[1]);
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

}

回答by Gypsy

import java.io.*;

public class Duplicate {

    public static void main(String[] args) throws IOException {
        int distinct = 0;
        int i = 0, j = 0;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter STRING : -");
        String s = br.readLine();
        try {
            for (i = 0; i < s.length(); i++) {
                while (s != null) {
                    s = s.trim();
                    for (j = 0; j < s.length(); j++) {
                        if (s.charAt(i) == s.charAt(j)) {
                            distinct++;
                        }
                    }
                    System.out.println(s.charAt(i) + "--" + distinct);
                    String d = String.valueOf(s.charAt(i));
                    s = s.replaceAll(d, " ");
                    distinct = 0;
                }
            }
        } catch (Exception e) {}
    }
}

回答by Syed Salman Hassan

public static void chars( String a, char k)
       {
           String z=""+k;
           int s=0;
           for(int i=0;i<a.length();i++)

           {

               if(z.equals(a.substring(i,i+1)))
                   s++;

                                            }

           System.out.println(s);
       }

you can achieve your goal this way you're taking the integer s without any reason and what you're doing wrong is you are using .contains() method instead of that you should compare the given char with each char of the string and use a counter for maintaining number of times of the character or you can do it this way by converting the char into a string by concatenating it with an empty string("") and then use .equals method like i have used in my code.

您可以通过这种方式实现您的目标,您可以毫无理由地使用整数 s,而您做错的是使用 .contains() 方法,而不是您应该将给定的字符与字符串的每个字符进行比较并使用用于维护字符次数的计数器,或者您可以通过将字符与空字符串(“”)连接来将字符转换为字符串,然后使用 .equals 方法,就像我在我的代码中使用的那样。