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 ?

4
  • 7
    Use std::string. You can't modify the contents of string literals. Commented Sep 28, 2012 at 14:19
  • i am using a library that gives me const char* . Commented Sep 28, 2012 at 14:20
  • 2
    Which is implicitly convertible to a string, and can easily be changed back. Commented Sep 28, 2012 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](stackoverflow.com/questions/164194/…) Commented Jun 18, 2022 at 10:32

2 Answers 2

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(); 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.