java - 将字符串更改为 Char 数组

标签 java string for-loop char

一旦将一个值存储为字符串,您如何循环遍历字符串并将每个值分配给一个字符数组?还必须计算数组中每个元音的出现次数。

这是我当前的代码:

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);

  }

}

最佳答案

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

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

str.charAt(i);

关于java - 将字符串更改为 Char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918190/

相关文章:

java - 将2的补码中的2字节整数从二进制文件读取为整数

java - 解析多个单词组合的字符串的最佳方法是什么?

python - 定义二进制文件字符串的类型

python - 如何从第二项迭代python dict

python - 我如何打印这样的图案

java - 如何检查数据库中是否存在 Oracle View ?在执行查询之前

Java 应用程序等待完成 java exec 命令才能再次正常工作

string - 实现字典的最佳数据结构?

r - 如果语句条件错误在两个和问题中缺少值?

java - 如何将 args 传递到我在 Play 2 中编写的自定义方法中?