将字符串转换为字符数组

3
一旦将一个值存储为字符串,如何循环遍历字符串并将每个值分配给字符数组?必须计算数组中每个元音字母的出现次数。
这是我目前的代码:
public class Part1_5 {

  /**
   * Method that gets user name and stores it as a string. Each value then
   * assign to a char array. no of vowels are counted and no of each printed
   */
  public static void main(String[] args) {

    // Setting up scanner
    Scanner scanner = new Scanner(System.in);

    // declaring string for name
    String userName = null;

    // declaring ints to hold total no of each vowel
    int totalOfA = 0;
    int totalOfE = 0;
    int totalofI = 0;
    int totalofO = 0;
    int totalofU = 0;

    // Get user input for name
    System.out.println("Please enter your Name...");
    userName = scanner.nextLine();

    for (int loop = 0; loop < userName.length(); loop++) {

      // declaring char array
      char[] letter = userName.toCharArray();

      if (userName.charAt(0) == 'a') {

        totalOfA++;

      }

    }

    System.out.println(totalOfA);

  }

}

一个字符串基本上就是一个带有一些额外细节的字符数组。但是没错...它已经基本上是一个字符数组了。 - Birb
谢谢您的回复!问题的初始部分是:“遍历字符串并将每个值分配给字符数组”。我想知道如何在我的代码中实现这一点,或者它是否已经完成了? - user2971033
使用您的编码方式(尽管Nick G的方式肯定更好,但对您来说可能还有点太高级了),删除char[] letter = userName.toCharArray();并将if (userName.charAt(0) == 'a') {替换为if (userName.charAt(loop) == 'a') {,如pobrelkey所建议的。现在,您必须对其余的元音字母执行相同的操作(使用loop作为索引进行if条件和计数)。请注意,此当前实现仅捕获a,而不是A。您可以通过编写if (userName.charAt(loop) == 'a' || userName.charAt(loop) == 'A') {来解决这个问题。再次强调,这种方式并不美观。 :) - Birb
在现实世界中,您不需要将username中的值复制到数组中以计算元音字母,因为您可以使用username.charAt()单独获取字符值。即使出于某种原因您确实想从一个String创建一个char数组,那么您只需调用yourString.toCharArray()即可。另一方面,如果您的教授要求您编写不必要的代码只是为了展示您知道如何实例化一个数组并寻址其元素,那就是另一回事了... - pobrelkey
我现在已经找到了解决方案,非常感谢大家!如果您不介意的话,是否有任何关于Stack Overflow的板块,我可以为像我这样的新手编写答案,针对我熟悉的内容?我想回答我知道的问题,而不仅仅是一直接收它们!哈哈 - user2971033
4个回答

2
String str = "stackoveflow";
char[] aa= str.toCharArray();

要直接从字符串中获取一个字符,您可以使用:

str.charAt(i);

2

如何迭代(并计数)字符串中的所有字符?

统计元音字母的数量是否需要区分大小写?

Map<Character, Integer> count = new HashMap<Character, Integer>();
char[] chars = "this is a test".toCharArray();
for (char curr : chars){
    Integer tmp = count.get(curr);
    if (tmp == null){ tmp = new Integer(0); }
    tmp++;
    count.put(curr, tmp);    
}
System.out.println(count.get("a".charAt(0)));
System.out.println(count.get("e".charAt(0)));
System.out.println(count.get("i".charAt(0)));
System.out.println(count.get("o".charAt(0)));
System.out.println(count.get("u".charAt(0)));

这将为您提供...

1
1
2
null
null

处理空值很简单 - 例如:result == null ? 0 : result

编辑:加入了100%的大小写不敏感性!!

Map<Character, Integer> count = new HashMap<Character, Integer>();
for (char curr :  "this IS a test".toLowerCase().toCharArray()){
    Integer tmp = count.get(curr);
    count.put(curr, tmp == null ? 1 : ++tmp);
}

同样的事情,但是用Groovy来实现...

def count = "this IS a test".toLowerCase().collect().countBy{it}

0

for 循环 中使用计数变量指定在 userName String 中计算元音字母的位置。

而且,对于你正在进行的方法,你甚至不需要一个 char 数组。但是如果你确实需要一个,应该在开始 for 循环 之前定义它。为什么要创建这么多次呢?

你问如何循环遍历 String 并将每个值分配给 char 数组,但你不需要这样做:你可以像你刚才做的那样,使用 char[] letter = userName.toCharArray();

public class Part1_5 {
    public static void main(String[] args) {

        // Setting up scanner
        Scanner scanner = new Scanner(System.in);

        // declaring string for name
        String userName = null;

        // declaring ints to hold total no of each vowel
        int totalOfA = 0,totalOfE = 0,totalofI = 0,totalofO = 0,totalofU = 0;

        // Get user input for name
        System.out.println("Please enter your Name...");
        userName = scanner.nextLine();

        // declaring char array (declare it once, before the loop)
        char[] letter = userName.toCharArray();

        for (int loop = 0; loop < userName.length(); loop++) {

            // check and count for any vowel at every iteration of the loop
            if (userName.charAt(loop) == 'a')
                totalOfA++;
            else if (userName.charAt(loop) == 'e')
                totalOfE++;
            else if (userName.charAt(loop) == 'i')
                totalOfI++;
            else if (userName.charAt(loop) == 'o')
                totalOfO++;
            else if (userName.charAt(loop) == 'u')
                totalOfU++;
        }
        System.out.println(totalOfA);
    }
}

0
if (userName.charAt(loop) == 'a') {

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接