0

I wanted to write a code that would delete a given character from a string. I have come up with the following snippet.

Now, while this does my work, it is giving me a worst case complexity of O(n^2). Can anyone help me on improving this.

#include<iostream.h> #include<conio.h> #include<stdio.h> void Push(char *, int i); int n=6; int main() { clrscr(); char *p = "helelo"; char delChar = 'e'; for(int i=0;i<5;i++) { if(*(p + i) == delChar) { Push(p, i); } } cout<<p<<endl; getch(); return 1; } void Push(char *p, int i) { for(int k=i;k<n;k++) { *(p + k) = *(p+k+1); } } 

Thanks

1
  • You should walk through the list once, and when you find the character you want to remove, step through the list from that point but copy the next element into the current one as you do. Also, why aren't you using std::string/char arrays, not doing p[k] instead of manual indexing, and returning 1 (0 is success)? Commented Oct 31, 2010 at 4:51

4 Answers 4

4
#include <cstring> #include <algorithm> #include <iostream> int main() { using namespace std; char s[] = "helelo"; cout << s << '\n'; char *end = s + strlen(s); end = remove(s, end, 'e'); *end = '\0'; cout << s << '\n'; // hllo return 0; } 

Note you can't modify string literals, so I used a char array. A std::string would be even easier.

If you want to understand how std::remove works, the char* instantiation (since it's a template) would, to keep it simple, look something like:

char* remove(char *begin, char *end, char value) { char *next = begin; for (; begin != end; ++begin) { if (*begin != value) { *next++ = *begin; } } return next; } 
Sign up to request clarification or add additional context in comments.

2 Comments

A std::string is not guaranteed to be NUL terminated. So I guess std::string s = "helelo"; *std::remove(s.begin(),s.end(),'e') = '\0' wont work.
@Prasoon: Actually, 0x changes string in that area, but I don't recall all the exact details. However, with a std::string, you use the erase method instead, just like you use s.length() instead of strlen. :)
0

An idea is to construct a new string from the first one using only valid characters(ones different from the unwanted character), then initialize first string with the one constructed.

Comments

0

Something like this should do it:

char *p = "helelo"; char delChar = 'e'; int len = strlen(p); for(int j=0, int i=0;i<len;i++) { if(*(p + i) != delChar) { *(p+j)=*(p+i); ++j; } } *(p+j)='\0'; cout<<p<<endl; getch(); return 1; 

Comments

0

How about:

int main() { clrscr(); char *p = "helelo"; char delChar = 'e'; int k=0; for( int i=0; *(p+i); i++ ) { if(*(p + i) != delChar) { *(p + k++) = *(p + i); } } *(p + k) = '\0'; cout<<p<<endl; getch(); return 1; } 

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.