Curlystraw
Curlystraw

Reputation: 295

Get part of a char array

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()?

Upvotes: 17

Views: 90613

Answers (5)

smac89
smac89

Reputation: 43078

Since C++17, you can use std::string_view to accomplish this:

char arry[20] = "hello world!";
auto part = std::string_view{arry, 5};
std::cout << part;

See it here: https://coliru.stacked-crooked.com/a/7ca65f2c8e8e46b4


C++20 also includes std::span, which is an option if you want to deal with ranges that are not just characters.

Upvotes: 0

Keith
Keith

Reputation: 6834

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_);
    }
};

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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);

Upvotes: 19

Moo-Juice
Moo-Juice

Reputation: 38825

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;

Upvotes: 5

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30969

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.

Upvotes: 25

Related Questions