S
S
shvaidahder2018-03-08 01:01:05
C++ / C#
shvaidahder, 2018-03-08 01:01:05

How to remove part of a string in c++?

Comrade, I need help! I'm trying to implement a function with strings (not using the string class!!!) and then I ran into a small problem. I explain the essence: there are two c-strings, suppose s1 = "how do you feel" and s2 = "how". the program must find the string s2 in the string s1, and if there is one, s1 must get rid of the string s2, that is, the output should be "do you feel". There are no problems with finding elements, but I'm a little stuck with deleting. wrote as s1[i] = s1[i + strlen(s2)] (with the corresponding condition, of course), but, of course, a mistake. and here the question is: how to shift the string by the required number of elements without string methods?
I would be very grateful for your help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mercury13, 2018-03-08
@shvaidahder

That's right, but only one thing is missing: somehow cut off the string after all this.

for (…)
  s1[i] = s1[i + s2len]
s1.resize(s1.length() - s2len);

Don't forget: if your string's length is strlen, then you can't call length() in the loop!
Yes, another question: remove the FIRST occurrence or ALL occurrences?

R
res2001, 2018-03-08
@res2001

You just need to copy the rest of the string to the beginning of the found substring.
I think it's best to use the memmove() function of the standard C library.
And at the end, do not forget to stick a null character.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question