0

For example,

std::string_view strv{ "Hello" };
strv.remove_prefix(1);

The original string should be "Hello".
I tried using strv.data() and std::string str(strv.begin(), strv.end());
I can only get "ello" instead of "Hello".

7
  • 9
    You remove the first character (h) with strv.remove_prefix(1), why would you expect anything other than "ello"? Commented Nov 17, 2021 at 15:37
  • The data() member returns a pointer to the first element of the view, not to the first element of the original string. Same goes for the iterators. The reason is that a view is like a window open on an actual container, not the container itself. Commented Nov 17, 2021 at 15:44
  • strv.data() - 1? but it is now outside of the view... Commented Nov 17, 2021 at 15:45
  • Does anyone know if it would be undefined behavior to access strv.data() - 1? Commented Nov 17, 2021 at 15:48
  • 3
    @JohnFilleau It should be fine, as data points into an array to a position where data() - 1 is still inside that same array. AFAIK the pointer arithmetic rules say that is okay. Commented Nov 17, 2021 at 15:52

2 Answers 2

1

I only found two methods right now.

  1. use a variable(e.g. string str) to store original string then use use string_view. When you need the original string, use str.

  2. use a variable(e.g. int removed_len) to record the length of removed prefixes. Then when you need the original string strv.data() - removed_len is the start place of the original string.

Sign up to request clarification or add additional context in comments.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

The "Hello" you use to construct strv is your original string. However, you never actually instantiate that string, making it a prvalue. If you want to keep a copy of your original string, try something like:

std::string str{"Hello"};
std::string_view strv{str};
strv.remove_prefix(1);

str will hold your original string.

1 Comment

Is it possible to find an original anonymous string?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.