我想在字符串中显示字符的出现。我该如何改进我的代码? [关闭]

问题描述 投票:2回答:8

我想创建一个程序,它将显示字符串中出现的字符数并计算它们。现在代码只计算字符数。

我想进行以下更改:

1)如何使这个程序只计算一种类型的字符,如字符串a中的cI love ice cream

2)如何在字符串中打印字符,假设有两个d,我的程序将首先显示2个d

3)对于Scanner input = new Scanner(System.in);部分我在我的日食中得到错误,说扫描仪无法解析为一种类型。

也可以随意评论代码中需要改进的任何内容。基本上只需要一个简单的程序来显示字符串中的所有C,然后计算字符串的出现次数。我想在我自己的代码中乱码,改变它以便我可以学习Java。

所以这是我的代码到目前为止:

public class Count { 
    static final int MAX_CHAR = 256; //is this part even needed?

    public static void countString(String str) 
    { 
        // Create an array of size 256 i.e. ASCII_SIZE 
        int count[] = new int[MAX_CHAR]; 

        int length = str.length(); 

        // Initialize count array index 
        for (int i = 0; i < length; i++) 
            count[str.charAt(i)]++; 

        // Create an array of given String size 
        char ch[] = new char[str.length()]; 
        for (int i = 0; i < length; i++) { 
            ch[i] = str.charAt(i); 
            int find = 0; 
            for (int j = 0; j <= i; j++) { 

                // If any matches found 
                if (str.charAt(i) == ch[j])  
                    find++;                 
            } 

            if (find == 1)  
                System.out.println("Number of Occurrence of " + 
                 str.charAt(i) + " is:" + count[str.charAt(i)]);             
        } 
    } 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str); 
    } 
} 
java string count find-occurrences
8个回答
2
投票

试试这个

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String str = input.nextLine();

    // Whatever is the input it take the first character.
    char searchKey = input.nextLine().charAt(0);
    countString(str, searchKey);
}

public static void countString(String str, char searchKey) {
    // The count show both number and size of occurrence of searchKey
    String count = ""; 
    for (int i = 0; i < str.length(); i++) {
        if (str.charAt(i) == searchKey)
            count += str.charAt(i) + "\n";
    }
    System.out.println(count + "\nNumber of Occurrence of "
                    + searchKey + " is " + count.length() + " in string " + str);
}

2
投票

您可以利用这样一个事实:每个char都可以用作数组的索引,并使用数组来计算每个字符。

public class Count {
static final int MAX_CHAR = 256; 

    private static void countString(String str, Character character) {
        int [] counts = new int[MAX_CHAR];
        char [] chars = str.toCharArray();
        for (char ch : chars) {
            if (character!=null && character!=ch) {
                continue;
            }
            counts[ch]++;
        }
        for (int i=0; i<counts.length; i++) {
            if (counts[i]>0) {
                System.out.println("Character " + (char)i + " appeared " + counts[i] + " times");
            }
        }
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();
        countString(str, 'e');
    }
}

1
投票
  1. 你可以从用户“他/她想要计算哪个角色”中获取输入。 要显示字符的出现,请参阅下面的代码。 您需要导入java.util.Scanner类。

这是你的代码:

import java.util.Arrays;
import java.util.Scanner;

public class Count { 

    public static void countString(String str) 
    { 

        if(str!=null) {
            int length = str.length(); 

            // Create an array of given String size 
            char ch[] = str.toCharArray();
            Arrays.sort(ch);
            if(length>0) {
                char x = ch[0];
                int count = 1;
                for(int i=1;i<length; i++) {
                    if(ch[i] == x) {
                        count++;
                    } else {
                        System.out.println("Number of Occurrence of '" + 
                                 ch[i-1] + "' is: " + count);
                        x= ch[i];
                        count = 1;
                    }
                }
                System.out.println("Number of Occurrence of '" + 
                     ch[length-1] + "' is: " + count);
            }
        }
    } 
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in); 
        String str =  input.nextLine();//"geeksforgeeks"; 
        countString(str); 
    } 
} 

1
投票

有关在Java8中执行此操作的方法,请参阅下面的代码段

public static void main(String[] args) {
    // printing all frequencies
    getCharacterFrequency("test")
            .forEach((key,value) -> System.out.println("Key : " + key + ", value: " + value));

    // printing frequency for a specific character
    Map<Character, Long> frequencies = getCharacterFrequency("test");
    Character character = 't';
    System.out.println("Frequency for t: " +
            (frequencies.containsKey(character) ? frequencies.get(character): 0));
}

public static final Map<Character, Long> getCharacterFrequency(String string){
    if(string == null){
        throw new RuntimeException("Null string");
    }
    return string
             .chars()
             .mapToObj(c -> (char) c)
             .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

}

1
投票

你只需要修改这行代码:

使用for loop,在str.charAt(i)声明中为count[str.charAt(i)时间打印if

    if (find == 1) { 
       for(int k=0;k< count[str.charAt(i)];k++)
          System.out.print(str.charAt(i)+",");
       System.out.println(count[str.charAt(i)]); 
    }

编辑:根据您的评论修改,如果您想要整个代码

  import java.util.*;

public class Count { 
static final int MAX_CHAR = 256; //is this part even needed?

public static void countString(String str) 
{ 
    // Create an array of size 256 i.e. ASCII_SIZE 
    int count[] = new int[MAX_CHAR]; 

    int length = str.length(); 

    // Initialize count array index 
    for (int i = 0; i < length; i++) 
        count[str.charAt(i)]++; 

    // Create an array of given String size 
    char ch[] = new char[str.length()]; 
    for (int i = 0; i < length; i++) { 
        ch[i] = str.charAt(i); 
        int find = 0; 
        for (int j = 0; j <= i; j++) { 

            // If any matches found 
            if (str.charAt(i) == ch[j]){  
                 //System.out.println(str.charAt(i));
                find++;  
            }                   
        } 

    if (find == 1) { 
       for(int k=0;k< count[str.charAt(i)];k++)
          System.out.print(str.charAt(i)+",");
       System.out.println(count[str.charAt(i)]); 
    }

    } 
} 
public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 
    String str = "geeksfeorgeeks"; 
    str = input.nextLine();
    countString(str); 
} 
} 

产量

g,g,2
e,e,e,e,e,5
k,k,2
s,s,2
f,1
o,1
r,1

1
投票

我知道你是初学者,但如果你想尝试新版本的java 8功能,这使我们的编码生活简单易行,你可以试试这个

public class Count {
 static final int MAX_CHAR = 256;
 public static void main(String[] args)    {
     Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str, 'e'); 
 }
 public static void countString(String str, char value) 
 { 
     List<String> l = Arrays.asList(str.split(""));
     // prints count of each character occurence in string
     l.stream().forEach(character->System.out.println("Number of Occurrence of " + 
             character + " is:" + Collections.frequency(l, character)));
     if(!(Character.toString(value).isEmpty())) {
         // prints count of specified character in string
         System.out.println("Number of Occurrence of " + 
                 value + " is:" + Collections.frequency(l, Character.toString(value)));
     }

 } 

这是注释中提到的要求的代码

public class Count {
static final int MAX_CHAR = 256;
 public static void main(String[] args)    {
     Scanner input = new Scanner(System.in); 
        String str = "geeksforgeeks"; 
        countString(str, 'e'); 
 }
 public static void countString(String str, char value) 
 { 
     String[] arr = str.split("");
     StringBuffer tempString = new StringBuffer();
     for(String s:arr) {
         tempString.append(s);
         for(char ch:s.toCharArray()) {
             System.out.println("Number of Occurrence of " + 
                     ch + " is:" + tempString.chars().filter(i->i==ch).count());
         }
     }
     if(!(Character.toString(value).isEmpty())) {
         StringBuffer tempString2 = new StringBuffer();
         for(String s:arr) {
             tempString2.append(s);
             for(char ch:s.toCharArray()) {
                 if(ch==value) {
                 System.out.println("Number of Occurrence of " + 
                         ch + " is:" + tempString2.chars().filter(i->i==ch).count());
                 }
             }
         } 
     }

   } 
} 

0
投票

您可以在下面使用此代码;

import java.util.Scanner;

public class Count {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String str = input.nextLine();

        char key = input.nextLine().charAt(0);
        countString(str, key);
    }

    public static void countString(String str, char searchKey) {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == searchKey)
                count++;
        }
        System.out.println("Number of Occurrence of "
                + searchKey + " is " + count + " in string " + str);

        for (int i = 0; i < count; i++) {
            System.out.println(searchKey);
        }

        if (count > 0) {
            System.out.println(count);
        }
    }
}

0
投票

我会创建一个如下所示的方法:

public static String stringCounter(String k) {
    char[] strings = k.toCharArray();
    int numStrings = strings.length;
    Map<String, Integer> m = new HashMap<String, Integer>();
    int counter = 0;
    for(int x = 0; x < numStrings; x++) {
        for(int y = 0; y < numStrings; y++) {
            if(strings[x] == strings[y]) {
                counter++;
            }

        }m.put(String.valueOf(strings[x]), counter);

        counter = 0;
    }
    for(int x = 0; x < strings.length; x++) {
        System.out.println(m.get(String.valueOf(strings[x])) + String.valueOf(strings[x]));
    }
    return m.toString();
  }



}

显然,正如你所做的那样,我会将String作为参数传递给stringCounter方法。在这种情况下,我会将String转换为charArray,我还会创建一个映射以存储String作为键,并存储一个Integer,表示单个字符串在字符数组中出现的次数。变量计数器将计算单个String出现的次数。然后我们可以创建一个嵌套的for循环。外部循环将遍历数组中的每个字符,内部循环将它与数组中的每个字符进行比较。如果匹配,计数器将递增。嵌套循环完成后,我们可以将字符连同循环中出现的次数一起添加到Map中。然后我们可以在另一个for循环中打印结果,遍历map和char数组。我们可以打印出你提到的角色出现的次数以及值。我们也可以返回看起来更干净的地图的String值。但是,如果您不想返回地图,则可以简单地使此方法无效。输出应如下:

我通过输入字符串“Hello world”在main方法中测试了该方法:

System.out.println(stringCounter("Hello World"));

这是我们的最终输出:

1H
1e
3l
3l
2o
1 
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}

您将获得字符串中每个字符出现的次数,您可以使用Map或打印输出。

现在为你的扫描仪。要在此处将Scanner添加到程序,您需要在代码顶部添加代码以提示用户输入String:

Scanner scan = new Scanner(System.in);
System.out.println("Please enter  a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));

您必须首先创建Scanner对象,将System.in添加到构造函数以从键盘获取输入。然后,您可以使用print语句提示用户输入String。然后,您可以创建一个String变量,该变量将通过调用“Scanner.nextLine()”方法作为值来存储String。这将从键盘获取下一行用户输入。现在您可以将userinput传递给我们的方法,它将以相同的方式运行。以下是用户应该看到的内容:

Please enter  a String: 
Hello World
1H
1e
3l
3l
2o
1 
1W
2o
1r
3l
1d
{ =1, r=1, d=1, e=1, W=1, H=1, l=3, o=2}
© www.soinside.com 2019 - 2024. All rights reserved.