简体   繁体   English

Java-如何更改名称为字符串的变量

[英]Java - How to alter a variable with its name as a String

Okay, perhaps that was a little hard to understand. 好吧,也许有点难以理解。

I'm trying to count all the letters in a string and eventually print all the counts, and I'd like to know how to change the count of a character in my loop. 我试图对字符串中的所有字母进行计数,并最终打印出所有计数,而且我想知道如何在循环中更改字符的计数。

Currently it goes like this: 目前它是这样的:

for (int i = 0; i<line.length();i++){
    line.charAt(i)++;
}

I have all the variable names as one character which they each represent, as in: int a=0,b=0,c=0,d=0,e=0,f=0 etc 我将所有变量名作为一个字符分别表示,例如:int a = 0,b = 0,c = 0,d = 0,e = 0,f = 0等

How do I use the ++ operator in this situation? 在这种情况下如何使用++运算符? line.charAt(iter) gives me a character, but how do I use that character as a variable? line.charAt(iter)给我一个字符,但是如何使用该字符作为变量?

This is not possible. 这是不可能的。

To do it correctly you should use a Map . 要正确执行此操作,您应该使用Map Store all this letters in a map of type Map<Character, Integer> . 将所有这些字母存储在Map<Character, Integer>类型的Map<Character, Integer> Then you can update values like this: 然后,您可以像这样更新值:

// assumming your data looks like this:
Map<Character, Integer> map = new HashMap<>();
map.put('a', 0);
map.put('b', 0);
// etc..., you should probably init these in a loop


// then you can do
for (int i = 0; i<line.length();i++){
    map.compute(line.charAt(i), i -> i+1);
}

You could collect the counts using an int array. 您可以使用int数组来收集计数。

int[] counts = new int[256];
for (int i = 0; i < line.length(); i++){
    counts[line.charAt(i)]++;
}
a = counts['a'];
b = counts['b'];
...

If you're dealing with only lowercase letters, you can keep an array of counts for an old school "C style" approach: 如果您只处理小写字母,则可以保留旧式“ C风格”方法的一系列计数:

int[] counts = new int[26];

then in your loop: 然后在您的循环中:

counts[line.charAt(i) - 'a']++;

Alternatively, there's the easier, 1-line way: 另外,还有一种更简单的一线方式:

Map<Integer, Long> frequency = line.chars().boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting()));

Where the key of the map is the integer value of the char. 映射的键是char的整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM