abseil / abseil-cpp

Abseil Common Libraries (C++)

Home Page:https://abseil.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

absl::StrReplaceAll replace '\0'

daixiang0 opened this issue · comments

  std::cout << absl::StrReplaceAll("a:b\0c", {
                                                 {"\0", "_"},
                                                 {":", "_"},
                                             });

Expect a_b_c but print a_bc.

The issue is the embedded \0 char. \0 is the delimiter for a const char*, so a const char* ends as soon as a \0 character is encountered.

This is another way of saying that if you treat a const char* as a string, then
const char* str = "ab\0c";
behaves as if it were
const char* str = "ab";

If you want to work with a string that has a embedded \0 chars, you need to explicitly specify the length of the string. For your example, you would need to write:

std::cout << absl::StrReplaceAll(absl::string_view("a:b\0c", 5),
                                   {
                                       {absl::string_view("\0", 1), "_"},
                                       {":", "_"},
                                   });

Thanks a lot, it helps me.