Counting characters in an array

How do I count how many characters of a string are stored in an array?

For example:
1
2
3
4
5
6
7
int main()
{
	char a[40] = "ABCDE";
	char b[40] = "FGHIJ";
	
	system("PAUSE");
}


Array a would be like this |A|B|C|D|E| | | | | |... <40 spots max>
Array b would be like this |F|G|H|I|J| | | | | |... <40 spots max>

I want to know how many spots in the array it used, so for example, array a has 5 spots and array b has 5 as well, so I know a[4] is the last box in the array ditto for b. So, i = 4.

What I'm basically trying to do is depending on how many how far in the array the characters went, I am going to do an addition problem like this:

ABCDE
FGHIJ+
-----

so lets say the value of E is 10 and the value of J is 5, I want to find them using i and work my way down. So, i = 4, then a[i]+b[i] = a[4]+b[4] = 10+5.

Get what I mean? I'm just basically counting the characters of a string that is being inputted into the array and storing that number into i.

Does anyone know how to do this?
Last edited on
Nevermind, I figured out a way.

1
2
3
4
5
6
7
8
9
10
11
12
int i = 0;
int j = 0;
while (a[i] != NULL)
{
	i+=1;
}
while (b[j] != NULL)
{
	j+=1;
}
i = i-1;
j = j-1;
Last edited on
Cool!

But why the -1 ? It should be correct without taking 1 off?

Note that, strictly speaking, NULL is for pointer. And a[i] isn't a pointer, it's a char. So you should really test against '\0' (the 0 char). By chance, NULL == 0 == '\0' so it works. But you're comparing different types (NULL is a int with value 0 in the C++ case)

1
2
3
4
5
6
7
8
const char a[] = "cool";
int j = 0;
while (a[i] != '\0')
{
	i+=1; // or ++i;
}

cout << i << endl;


a = 'c', 'o', 'o', 'l', '\0'

i = 0 -> 'c' != '\0' -> test is true -> increment to 1
i = 1 -> 'o' != '\0' -> test is true -> increment to 2
i = 2 -> 'o' != '\0' ->  test is true -> increment to 3
i = 3 -> 'l' != '\0' -> test is true -> increment to 4
i = 4 -> '\0' != '\0' -> test is false -> breakloop with 4

And 4 is (the length) of "cool" !!

Andy
Last edited on
I think i and j are the last valid index, not the length (n -1,) but it would make more sense to store the length.
Have you read my work through? The loop terminates when it reaches the null teminator at index 4. Which is the length of the string "cool". (by convention, the null terminator is not counted)
Last edited on
In c and C++ all strings are arrays which end with NULL
C++ provides function length() to get the length of a string
1
2
3
string s;
s="abcde";
s.length();//prints 5 
Topic archived. No new replies allowed.