tags:

views:

65

answers:

4

Hi,

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

A: 

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.

Csaryus
+4  A: 
#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;
}
Roger Pate
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 Saurav
@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. :)
Roger Pate
A: 

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;
Lee
A: 

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;
}
LavaSlider