can u please temme the string funtion which will eliminate the character in the desired position in C++.
ie in (string.h)

example
i need to remove the 4th character in "SACRED"
so the resultant array must be "SACED"
without a blank space in the deleted postion.
so the size gets reduced by one.
i am new to this field.. help me put pls

Recommended Answers

All 13 Replies

string s = "SACRED";
s.erase(3,1);
string s = "SACRED";
s.erase(3,1);

.. thanks...
but i hav tried this one out , but in turbo Cpp compiler...
it pops an error tat.. dot operator is (.) is not allowed..
is it the exact function...

i need explanation pls...

You need to post what you are attempting to do because its a little difficult for us to see your computer screen :) But I suspect you are asking about character arrays insterad of c++ strings.

If that's the case, there are a couple ways to do it. One way is to use strcpy() function

char str[] = "SACRED";
strcpy( &str[2], &str[3]);

I didn't compile or test that, but I think it will work.

.. thanks...
but i hav tried this one out , but in turbo Cpp compiler...
it pops an error tat.. dot operator is (.) is not allowed..
is it the exact function...

The code is ok, but codeaa probaly uses a using namespace std; in his code. Although this works, it is recommended to type in the namespace manually due to overhead.
So try this:

std::string s = "SACRED";
s.erase(3,1);

And don't forget to #include <iostream> Niek

[edit] too slow again.. Use Ancient Dragon's solution of you're working with char[]

niek_e is right and I should have explained more.

The erase function takes two parameters. The first is the index of the character to be removed and the second is the number of characters to be removed.

is the s.erase user defined fuction ?? coz I can't find it anywhere in c++ help.

is the s.erase user defined fuction ?? coz I can't find it anywhere in c++ help.

Which version of C++ are you using? It is not there in Turbo C++.

If that's the case, there are a couple ways to do it. One way is to use strcpy() function

char str[] = "SACRED";
strcpy( &str[2], &str[3]);

I didn't compile or test that, but I think it will work.

Undefined behavior.

strcpy copies strings so far my teacher has taught me a very tough prog that is

if the array index of element is x,
overite by doing x-1.

Undefined behavior.

Source and destination strings do not overlap, they are simply in the same buffer, so where's the undefined behavior?

Source and destination strings do not overlap, they are simply in the same buffer, so where's the undefined behavior?

Oops, sorry, my bad.

From what I read in those links looks like I was wrong. Should have used memmov() instead of strcpy().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.