Get part of a char array

2020-02-10 18:42发布

问题:

I feel like this is a really silly question, but I can't seem to find an answer anywhere!

Is it possible to get a group of chars from a char array? to throw down some pseudo-code:

char arry[20] = "hello world!";
char part[10] = arry[0-4];
printf(part);

output:

hello

So, can I get a segment of chars from an array like this without looping and getting them char-by-char or converting to strings so I can use substr()?

回答1:

In short, no. C-style "strings" simply don't work that way. You will either have to use a manual loop, or strncpy(), or do it via C++ std::string functionality. Given that you're in C++, you may as well do everything with C++ strings!

Side-note

As it happens, for your particular example application, you can achieve this simply via the functionality offered by printf():

printf("%.5s\n", arry);


回答2:

You could use memcpy (or strncpy) to get a substring:

memcpy(part, arry + 5 /* Offset */, 3 /* Length */);
part[3] = 0; /* Add terminator */

On another aspect of your code, note that doing printf(str) can lead to format string vulnerabilities if str contains untrusted input.



回答3:

As Oli said, you'd need to use C++ std::string functionality. In your example:

std::string hello("Hello World!");
std::string part(hello.substr(0, 5)); // note it's <start>, <length>, so not '0-4'

std::cout << part;


回答4:

Well, you do mention the two obvious approaches. The only thing I can think of would be to define your own substring type to work off character arrays:

struct SubArray
{
    SubArray(const char* a, unsigned s, unsigned e)
        :arrayOwnedElseWhere_(a),
        start_(s),
        end_(e)
    {}
    const char* arrayOwnedElseWhere_; 
    unsigned start_;
    unsigned end_;
    void print()
    {
        printf_s("%.*s\n", end_ - start_ + 1, arrayOwnedElseWhere_ + start_);
    }
};


标签: c++ arrays char