简体   繁体   中英

Getting character values from an array of strings

I'm trying to practice some c++ stuff and have gotten stuck on something which has been difficult to google or find the answer too.

basically say we have:

char* myarray[] = {"string","hello", "cat"};

how would I got about say getting myarray[1] which is "string" and then traversing through the letter strin g.

I was looking at vectors and wonder if that is the route to take or maybe taking myarray[1] and storing it into another array before iterating through it. What is the best way of doing this

That's very easy in C++11 (using std::string rather than a pointer to an array of characters):

#include <iostream>
#include <string>

int main()
{
    std::string myarray[] = {"string","hello", "cat"};
    for (auto c : myarray[0]) { std::cout << c << " "; }
}

Output ( live example ):

s t r i n g

The following code:

for(int i = 0; i < strlen(myarray[0]); i++) {
    printf("%c\n", myarray[0][i]);
}

Will print out

s
t
r
i 
n
g

If you're looking to practice C++ and not C , I suggest learning std::string and std::vector . They are not always the solution but usually using them first is the right answer. The memory layout of std::vector<std::string> will be different and it is important to understand this.

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