counting to the '\0' on the array of char

Hi I'm just about pulling my hair..
I can seem to figure out how to count to the end of the word, in an array of char

see below, the code.. take a look at the char str2 is an array, with "or not to be"..

I want to count to the end of the word "or"

What I understand, is that after each continuous set of char, there is an automatic '\0'..?

I'm obviously doing something really wrong.. anyone can help me out here?
How can I count to the end of the word "or" and return the index for the "r" or the space?


1
2
3
4
5
6
char str2[20];
strcpy (str2,"or not to be");
int SIZE = strlen(str2), ewidx=0;
for (int i = 0; i < SIZE; i++)
   if (str2[i] == '\0')
      ewidx = i;
strlen will return the value 12 (decimal) this does not include the terminating 0.
this means that the characters start at index 0 and end at index 11 (decimal).
The terminating 0 will be at index 12.

so if your loop starts and 0 and end at less than size (which is 12) then the loop only goes
from 0 to 11 which means it never reaches the terminating 0;

what you need is i <= SIZE;
Hey guestgulkan,

thanks for your response, however - I am already using the strlen, however - I am trying to count to the next word.. I'm super novice at c++, so I dont know, if its at the end of the string, where the terminiating \0 is, or at the end of each word..

currently, I found an isspace and iscntrl function.. its closer, to what I'm looking for, but still getting the wrong numbers..

lets take a for instance, and continue with the string above.. str2, that contains "or not to be"
want to count "or" then the function to return 1, being the end of the word.. o is 0 index, and r is 1 index...

here is the code i have started. (please dont mind the variables, its the actual program I am working with for my class assignment)

1
2
3
4
5
while (!iscntrl (eng[ewidx]) || !isspace (eng[ewidx]) || eng[ewidx] == NULL) 
{
      ewidx++;
}
return ewidx;
Last edited on
sorry, my mistake, i misread the actual question - I was going by the title of the thread.
There are a number of ways to do this. you are making it way too complex for yourself. First, can you write C++ code or is this a C program? Please clarify.

It can be done with a very simple for loop but I am confused as to what you are trying to do. There are multiple words in the string? Do you want an array of counters that counts the size of each word? Which word are you trying to count? Are you trying to count the total number of letters?

What I understand, is that after each continuous set of char, there is an automatic '\0'..?


I don't understand that comment. There is a '\0' at the end of the entire string not at the end of each word. Between each word is simply a ' ' character right? You don't need a for loop to tell you where the '\0' is so your original for loop is perplexing. I still don't understand what you want to do.
Topic archived. No new replies allowed.