I am trying to get the programme to firstly print the ascii values of the first ten chars in the array s. I am also trying to build a function that counts the number of 4 letter words typed into it.
Any help would be hugely appreciated, thanks!
This is a discussion on Help Needed please! (Basic) within the C Programming forums, part of the General Programming Boards category; I am trying to get the programme to firstly print the ascii values of the first ten chars in the ...
I am trying to get the programme to firstly print the ascii values of the first ten chars in the array s. I am also trying to build a function that counts the number of 4 letter words typed into it.
Any help would be hugely appreciated, thanks!
Last edited by Acer; 10-05-2010 at 12:42 PM.
You've got a start.
You could tokenize your string with strtok() and check the length of each token. If the length is 4 characters, increment a counter.
Counting can be done like this:
A integer and a character are basically the same thing, except since a character is simply 1 byte (typically), it can only count up to 255, while an integer is 4 bytes (typically). It's all how you choose to display the information (notice the variable formatting in the printf() function, the first one specifies that it be print out as a char, as one would expect, but the %d specifies that it be printed out as a decimal, which is its ASCII value.Code:char* buffer = "Hello World"; int i; for (i = 0 ; i < 10 && i < strlen(buffer) ; ++i) { printf("Letter %c in ASCII is %d\n", buffer[i], buffer[i]); }
As for counting the number of 4 letter words, use a string tokenizer, a fairly common tool for parsing strings.
A tokenizer takes a string (char buffer), and a string of characters representing delimiters (separators). Subsequent calls to the tokenizer take a NULL pointer as the first parameter which tells it to continue where it left off last time. The tokenizer will return a NULL pointer when there are no more tokens left.Code:int count = 0; char* buffer = "These are some words, not all of them are four letters" char* token = strtok(buffer, " \t"); while (token) { if (strlen(token) == 4) count++; token = strtok(NULL, " \t"); }
A token is just a "word" so to speak - that is, anything in between the delimiters, in the case above, I set the delimiters to spaces and tabs (general whitespace) with the string " \t".
Hope that helps ya out some.
God I hope that's not homework...
Feel free to PM me if you have any more specific questions, sometimes I don't see responses to my posts.
Last edited by Syndacate; 10-05-2010 at 12:24 PM.