0

i have

cost char* a="test_r.txt"

i want to strip the _r and add _n instead of it so that it becomes "test_n.txt" and save it in const char* b;

what is the easiest way to do it ?

rajat
  • 3,415
  • 15
  • 56
  • 90
  • 7
    Use `std::string`. You can't modify the contents of string literals. – chris Sep 28 '12 at 14:19
  • i am using a library that gives me const char* . – rajat Sep 28 '12 at 14:20
  • 2
    Which is implicitly convertible to a string, and can easily be changed back. – chris Sep 28 '12 at 14:21
  • Same question in C [c - Why do I get a segmentation fault when writing to a "char *s" initialized with a string literal, but not "char s[]"? - Stack Overflow](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-char-s-initialized-with-a) – user202729 Jun 18 '22 at 10:32

2 Answers2

5

You can't directly modify the contents of a, so you'll need some copying:

std::string aux = a;
aux[5] = 'n';
const char* b = aux.c_str();
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
1

Like mentioned before, if you put your const char * into a std::string, you can change your characters. Regarding the replacing of a constant that is longer than one character you can use the find method of std::string:

const char *a =  "test_r_or_anything_without_r.txt";

std::string a_copy(a); 
std::string searching("_r");
std::string replacing("_n");
size_t pos_r = 0;

while (std::string::npos != (pos_r = a_copy.find(searching, pos_r)))
{
    a_copy.replace(a_copy.begin() + pos_r,
                   a_copy.begin() + pos_r + searching.length(),
                   replacing.begin(), replacing.end());
}

const char *b = a_copy.c_str();
Uli Klank
  • 199
  • 10