Check if char exists in java

Go To StackoverFlow.com

0

If I have a string that contains "Cat" how could I check before hand if anything exists in each individual charAt case. Here is the sample code

    for (int i = 0; i < array.length; i++)
    {
        System.out.println();
        for (int j = 0; j < size; j++)
        {
            System.out.print(array[j].charAt(i) + " ");
        }
    }

Once i reaches 3 you would get an out of bounds exception. Is there a way that it could print an empty space?

EDIT: Sorry I wasn't clear at all. There are multiple strings that are being printed vertically. So assume the largest string is size of 10 and that the smallest is size of 4. The first four char of each string print fine. But an out of bounds error occurs when the fifth char tries to print since it doesn't exist. Is there any way around that?

2012-04-03 20:28
by HaniAA


7

You've got i and j the wrong way around, that's all.

You should have:

System.out.print(array[i].charAt(j) + " ");

And to make your code more robust, you should rewrite the inner loop to go until it reaches the length of array[i], instead of a pre-defined size variable.

Update: If you want to print the array of strings vertically (so each string is in a column), this is what your code should look like:

for (int i = 0; i < size; i++)             // i is the loop variable for the character count, we'll print one line for each character
{
    for (int j = 0; j < array.length; j++) // for every string in the array
    {
        char c = ' ';                      // print out a space character by default to keep the columns aligned
        if ( array[j].length() > i )       // but if the array[j] still has characters left
            c = array[j].charAt(i);        // print that character instead
        System.out.print(c + " ");         // here
    }
    System.out.println();                  // and close the line
}
2012-04-03 20:29
by biziclop
Also, I think size needs to be set to the array[i].length-1 - kevingreen 2012-04-03 20:30
@kevingreen: well, since the test is j < size, then size should be just array[i].length - Greg Hewgill 2012-04-03 20:32
@GregHewgill Yup, you are correct. For some reason I saw that as <=size. I think that's just my own tendencies for coding that way coming out - kevingreen 2012-04-03 20:33
Size hold the value of the largest string - HaniAA 2012-04-03 21:02
Thank you good sir. I was thinking way to hard into this - HaniAA 2012-04-03 21:24


1

how could I check before hand if anything exists in each individual charAt case.

Besides the indexing issue already mentioned by biziclop, you must also check the size of the string before you do a charAt.
I mean for (int j = 0; j < size; j++) here size should be array[j].length() for this to work.

But why bother with a loop iteration?
You can do just System.out.print(array[i] + " ");

2012-04-03 20:49
by Cratylus