我想创建一个程序,该程序将显示字符串中某个字符的出现次数并对其进行计数。现在,代码只计算字符。
我要进行以下更改:
1)我如何使该程序仅计算一种类型的字符,例如字符串a
中的c
或I 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);
}
}
答案 0 :(得分:2)
您可以利用以下事实:每个字符都可以用作数组的索引,并使用数组来计数每个字符。
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 :(得分: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 :(得分:1)
这是您的代码:
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);
}
}
答案 3 :(得分: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()));
}
答案 4 :(得分: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
答案 5 :(得分: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());
}
}
}
}
}
}
答案 6 :(得分: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);
}
}
}
答案 7 :(得分: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来存储单个字符串在字符Array中出现的次数。变量计数器将计算单个String出现多少次。然后,我们可以创建一个嵌套的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}
您将获得每个字符在String中出现的次数,您可以使用Map或打印输出。
现在使用扫描仪。要将扫描程序添加到程序中,以下是您需要在代码顶部添加的代码,以提示用户输入String:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a String: ");
String str = scan.nextLine();
System.out.println(stringCounter(str));
您必须首先创建Scanner Object,将System.in添加到构造函数中以从键盘获取输入。然后,您可以通过打印语句提示用户输入字符串。然后,您可以通过调用“ Scanner.nextLine()”方法作为值来创建一个String变量来存储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}