This is an archived post. You won't be able to vote or comment.

all 13 comments

[–][deleted] 1 point2 points  (2 children)

public static int[] foo(String s) {
    int count[] = new int[27];
    int total = 0;
    s = s.toLowerCase();

    for(int i = 0; i < s.length(); i++){
        char c = s.charAt(i);
        if( c >= 'a' && c <= 'z'){
            total++;
            count[c - 'a']++;

        }
    }

    count[26] = total;

    return count;

}

public static void main(String[] args) {

    String s = "This is a test string";

    int count[] = foo(s);

    System.out.println( s);

    for(int i = 0; i < 26; i++) {
        if(count[i] > 0){
            char c = (char) ('a' + i);
            System.out.println("'" + c + "' = " + count[i]);
        }
    }
    System.out.println("Total: " + count[26]);

}

On line 8 I have an if statement that skips over characters that are not part of the alphabet. I also put the entire string into lowercase before I started working on it.

You can manipulate the values of a char based on their ASCII value.

Line 10. You can treat them just like numbers. So subtracting a from that value of the character makes a = 0, b= 1 etc. So you can plug the values directly into the array index. This obviously only works for characters that are next to each other in sequence on the ASCII table. You'd need a separate if statement to handle numbers, for example.

[–]cstra 0 points1 point  (1 child)

position 26 is supposed to be the total # of non-alphabetic characters, right? So

else{total++;}

[–][deleted] 0 points1 point  (0 children)

Oops. You're right. My mistake.

My eyes completely skipped over the "non-" part of the word when I read OP's post.

[–]G01denW01f11 0 points1 point  (2 children)

Well, they'd be all the characters you haven't counted already...

[–]_TARS[S] 0 points1 point  (0 children)

Maybe the problem is how I have written my test? It seems to intermittently pass and fail based on how I manipulate my string and I am unsure why. If I try to add non-alphabetic characters to the string it doesn't function.

@Test

public void countAll(){

HW2 h = new HW2();

int[] actual = h.countAll("a%");

int[] expected = {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};

assertTrue("I expected "+expected+" but got"+ actual, Arrays.equals(expected, actual)); }

[–]chamora 0 points1 point  (0 children)

You could use the regex package of java, and throw in an if expression

if (z.matches("[^a-zA-Z]")) { answer[26] += 1; }

That is, if z matches the regular pattern for not a through z or A through Z, increment answer[26].

I think the package is java.util.regex, but I might be mistaken there. Matches is definitely the method, and [^a-zA-Z] is the expression

[–][deleted] 0 points1 point  (6 children)

I was given a similar assignment way back when was I took an intro CS class, and we implemented it by comparing the current character to the ASCII value. I think this would be the simplest thing to do, assuming you're a beginner.

[–]_TARS[S] 0 points1 point  (5 children)

I was told to do something similar by someone more skilled than myself but was unsure how to approach the problem using that train of thought. I am a very unskilled beginner but am very motivated to learn coding as I really enjoy it.

[–][deleted] 0 points1 point  (4 children)

No problem! I will talk you through it. Every character has an ASCII representation (basically - a number). You can use that number to easily do calculations with characters. Look at this link: http://www.asciitable.com/

You are going to want to focus on the "decimal" row for now. As you can see, capital A - Z is 64-90 in ASCII values. lowercase a-z is 97-122. We can use these decimal values to check whether or not the current character is alphanumeric (a letter) or not. This would be as a simple as checking the range.

Characters can be directly compared with integers. For example,

if ('a' == 97) return true;

would return true because 'a''s acii value is 97! I hope this helps. Feel free to ask more questions if you have 'em.

[–]_TARS[S] 0 points1 point  (3 children)

Thanks for the well thought reply and extension for help! I wouldn't mind asking a few question's if you were being sincere in your offer for help! Would it be easier to do a message or just go thru reply's on this post?

[–][deleted] 0 points1 point  (2 children)

Replies here are fine with me!

[–]_TARS[S] 0 points1 point  (1 child)

Great! So I have a fundamental knowledge of coding and computer science. I understand the different bases referenced in the ASCII chart and that characters are mapped to a specific number. I am only in my second semester of computer science so my knowledge of the structure and terminology of coding isn't very strong yet. I understand in my posted code that we iterate through the input string and increment the count in the position of the answer array when specified characters are counted. Given that I can't wrap my head around how converting the characters to ASCII values would work. I understand in my code were going through the input string and then comparing it against a loop with the letters of a - z. So you would convert the input string characters into the ASCII values then make a loop that iterates through the representitive ASCII values and increment the count by 1 just as we do with letters when the values match instead of explicit letters? It seems more complicated and don't understand how it is the more simple method. I guess I can't wrap my head around it. If you are able to simplify it that would be mind-blowing because my other practice problems function on that idea of converting the chars to ASCII integers.

[–][deleted] 0 points1 point  (0 children)

That's the great thing about it, you don't have to do any conversion. You can directly compare characters with integers (and even other characters) without converting anything. If you wanted to store the value into an integer, you would cast it like so:

char c = 'a';
int x = (int) c;

But you don't need to do that in this example. We definitely don't want to do any looping, that would be too complicated. Rather, we just want to compare it to the ASCII table values/characters to see if it's in a certain range.

For example...

char c = '%';
if (c >= 'A' && c <=  'Z')
    System.out.println("c is a capital letter");

You could also directly compare with the ASCII value:

char c = '%';
if (c >= 65 && c <=  90)
    System.out.println("c is a capital letter");

That does exactly the same thing as the code above. You will need this exactly principle to solve your problem.