这是参考代码:
// Create an array of size 256 i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int len = str.length();
// Initialize count array index
for (int i = 0; i < len; i++)
count[str.charAt(i)]++;
// Create an array of given String size
char ch[] = new char[str.length()];
for (int i = 0; i < len; 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)]);
}
输出应该类似于:
'x'的出现次数为:'出现次数'
如果之前发生了这封信,那么只显示一次。
我使用2 for循环获取逻辑,尽管我的老师说只使用1 for循环就可以执行此应用程序。
我遇到的问题是:
我能够找到角色是否已经被发现,只有它们彼此相邻。
如果没有其他for循环,你如何检查是否找到了所有前一个字符?
答案 0 :(得分:2)
使用Map<Integer, Integer>
(键:字符,值:字符数)来存储您的字符数。
你只需要循环一次你的角色:
String input = "this is input string";
Map<Integer, Integer> charCount = new LinkedHashMap<>();
for (int c : input.toCharArray()) {
if (!charCount.containsKey(c)) {
charCount.put(c, 1);
} else {
charCount.put(c, charCount.get(c) + 1);
}
}
// Here you print the char count:
for (Entry<Integer, Integer> entry : charCount.entrySet()) {
// (char) entry.getKey() is the character
// entry.getValue() is number of occurence
}
没有Map
:
int[][] count = new int[MAX_CHAR][2];
for (int c : input.toCharArray()) {
count[c][0] += 1; // Increase occurrence by 1
count[c][1] = 1; // Mark this character exists in string
}
// Here you can print the count of char per character
// Not that, you can use count[c][1] to determine that if the character exists in your String
for (int i = 0; i < MAX_CHAR; i++) {
if (count[i][1] == 1) {
System.out.println("Char: " + (char) i + " Occurence: " + count[i][0]);
}
}
修改强> 正如@oreh所说,我们甚至不需要二维数组:
int[] count = new int[MAX_CHAR];
for (int c : input.toCharArray()) {
count[c][0] += 1; // Increase occurrence by 1
}
for (int i = 0; i < MAX_CHAR; i++) {
if (count[i] > 0) {
System.out.println("Char: " + (char) i + " Occurence: " + count[i]);
}
}
答案 1 :(得分:0)
如果您只想找到例如字母,那么您就知道ASCII码的范围。在这种情况下,使用1D数组并将索引表示为带偏移的符号代码就足够了。例如。要查找只有字母,您可以创建数组int[] count = new int[26]
,int total_a = count[0]; // or count['a' - 'a']
包含a
的计数器,而对于z
我们有最后一个索引:int total_z = count[25]; // or count['z' - 'a']
:
public static void printLetterOccurrence(String str) {
int[] count = new int['z' - 'a' + 1];
str = str.toLowerCase();
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')
count[str.charAt(i) - 'a']++;
for (int i = 0; i < count.length; i++)
if (count[i] > 0)
System.out.println("Number of Occurrence of " + (char)('a' + i) + " is: " + count[i]);
}