3

Once a value is stored as a String, how can you loop through string and assign each value to a char array? The occurrences of every vowel in array must also be counted.

This is my current code:

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

  }

}
5
  • A String is basically a char array with a few extra details. But yeah... it's basically a char array already. Commented Nov 11, 2013 at 23:46
  • Thanks for your reply! The inital part of the question is: "Loop through the string and assign each value to a char array". I was wondering how to do this within my code, or has it already been done? Commented Nov 11, 2013 at 23:49
  • Using your way of coding it (while Nick G's way is definitely better, it may be a little too advanced for you, just yet), delete char[] letter = userName.toCharArray(); and replace if (userName.charAt(0) == 'a') { with if (userName.charAt(loop) == 'a') { as suggested by pobrelkey. Now you've gotta do the same (if-condition and counting with loop as the index) for the remaining vowels. Note that this current implementation only captures a, and not A. You could fix this by writing if (userName.charAt(loop) == 'a' || userName.charAt(loop) == 'A') {. Again, this way isn't pretty. :) Commented Nov 12, 2013 at 0:11
  • In the real world you wouldn't need to copy the values in username to an array to count the vowels, when you can just use username.charAt() to get the character values individually. And even if for some reason you did want to create an array of char from a String, you'd just call yourString.toCharArray(). On the other hand, if your professor is making you write unnecessary code just to show you know how to instantiate an array and address its elements, that's another matter... Commented Nov 12, 2013 at 0:12
  • I have got my solution now thanks a lot everyone! If you don't mind me asking, is there any section on stack overflow where I could write answers for novices like myself for content I am familiar with? I would like to be giving answers for questions I know rather than just always receiving them! lol Commented Nov 12, 2013 at 0:43

4 Answers 4

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

And to directly get a char from string, you can use:

str.charAt(i);
Sign up to request clarification or add additional context in comments.

Comments

2

What about iterating over (and counting) all characters in a String?

Does the count of the vowels have to be case sensitive?

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

Which gives you...

1
1
2
null
null

Handling null is trivial - e.g. result == null ? 0 : result

Edit: Improved with 100% more case insensitivity!!

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

And the same thing, but in Groovy...

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

Comments

0

Use the counting variable in the for loop to specify the position in the userName String to count up the vowels.

Also, you don't even need a char array for the method that you're doing. But if you did need one, you should define it before you start the for loop. Why create it so many times?

You asked how to loop through the String and assign each value to a char array, but you don't need to do that: you can simply do what you did, 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);
    }
}

Comments

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

Comments