拆分没有空格的输入
Splitting an input that doesn't have blank spaces
我有一个看起来像这样的输入 ABABABAABA
,我想将输入拆分为单个字符,然后计算字母 "A" 和 "B" 出现的次数。这是我目前所拥有的
import java.util.Scanner;
Scanner str = new Scanner(System.in);
String userInput = str.nextLine();
userInput.split("");
计算字母"A"和"B"出现了多少次后怎么办?
您将遍历您的字符串并读取带有 `String.charAt(index)' 的字符。根本不需要拆分。)。
int countA = 0;
int countB = 0;
for(int index = 0; index < userInput.length(); index++)
{
char c = userInput.charAt(index);
if(c == 'A')
{
countA++;
}
else if(c == 'B')
{
countB++;
}
else
{
// some other character detected
}
}
您实际上不需要拆分它,只需对其进行迭代就足够了。然后你可以使用地图来计算这样的出现次数:
Scanner str = new Scanner(System.in);
String userInput = str.nextLine();
Map<Character, Integer> occ = new HashMap<>();
for(char ch : userInput.toCharArray()) {
if(!occ.containsKey(ch)) {
occ.put(ch, 0);
}
occ.put(ch, occ.get(ch) + 1);
}
我有一个看起来像这样的输入 ABABABAABA
,我想将输入拆分为单个字符,然后计算字母 "A" 和 "B" 出现的次数。这是我目前所拥有的
import java.util.Scanner;
Scanner str = new Scanner(System.in);
String userInput = str.nextLine();
userInput.split("");
计算字母"A"和"B"出现了多少次后怎么办?
您将遍历您的字符串并读取带有 `String.charAt(index)' 的字符。根本不需要拆分。)。
int countA = 0;
int countB = 0;
for(int index = 0; index < userInput.length(); index++)
{
char c = userInput.charAt(index);
if(c == 'A')
{
countA++;
}
else if(c == 'B')
{
countB++;
}
else
{
// some other character detected
}
}
您实际上不需要拆分它,只需对其进行迭代就足够了。然后你可以使用地图来计算这样的出现次数:
Scanner str = new Scanner(System.in);
String userInput = str.nextLine();
Map<Character, Integer> occ = new HashMap<>();
for(char ch : userInput.toCharArray()) {
if(!occ.containsKey(ch)) {
occ.put(ch, 0);
}
occ.put(ch, occ.get(ch) + 1);
}