简体   繁体   中英

Length of string in array of string

I am trying to use the size of individual string in my code. here's what I have

const static char * keypad[] = {
    "ex",
    "bobbb",
    "test",
};

but when I try to use, for example,

sizeof(keypad[i]); 

it does not return the correct size for the each string. Is there anyway to do this in C++? I am limited to

#include <stdio.h> 
#include <ctype.h> 

for some arbitrary reason.

You can use the strlen function for each element of the array. If you can't use string.h then you can write your own. Just loop over each character until you find the terminating '\\0'.

Given your constraints (presumably by a teacher?) you have two tasks. One is to write your own strlen function. Two is to figure out how to loop over each element of the array. The second task boils down to figuring the length of the array (assuming you don't hard code it).

keypad is not an array of strings . It's an array of pointers , each of which points to (the first character of) a C-style string.

sizeof keypad[i] gives you the size in bytes of one of those pointers, probably 4 or 8 bytes.

The way to determine the length of a string (defined as the number of characters up to, but not including, the terminating '\\0' null character) is to call the strlen() function. If you're not allowed to use <string.h> , you'll have to write an equivalent function yourself.

(You could legally declare strlen without including <string.h> , but I presume that would be considered cheating, so I won't show you how to do it.)

(The real way to do this in C++ would be to define a std::vector<std::string> , but apparently you're not permitted to do this. Perhaps part of the point of the current exercise is to show you how much more convenient a different approach can be.)

sizeof(keypad[i]);

Is an array which stores the address. these address
address[0]

address[1]

address[2]

point to the string, as they are pointer which may have size 4 bytes or may vary depending on processor.

in order to get the complete size

#include<iostream>
#include<string.h>
using namespace std;
int main()
{
const static char * keypad[] = {
    "ex",
    "bobbb",
    "test",
};
int i,size=0;
for(i=0;i<sizeof(keypad)/sizeof(char*);i++)
{
    size=size+strlen(keypad[i]);
}
cout<<size;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM