Link to home
Start Free TrialLog in
Avatar of Amit
AmitFlag for United States of America

asked on

changing the size of a string

The following code tries to remove the character 's' from the string. But the code doesn't work, i know its becoz of the if condition. Please help me in creating function that actually modifies the original string.
_________________________________________________________________________
      char s[] ="hissalpha";

      cout << s << endl;


      char *p=s;
      char *q=s;


      while (*p)
      {
      
            if (*p !='s')
      
            {
            
                  cout << *p << endl;

                  *q=*p;
                  
                   q++;
            }

      
            p++;
      }

      cout << s << endl;
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

It works well, just need an ending null character after the last line:

*q = 0;
cout << s << endl;
ASKER CERTIFIED SOLUTION
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Amit

ASKER

i don't get it
>i don't get it
That means you haven't understood the problem?
I your code working well now?
Avatar of Amit

ASKER

tell me one thing, what happens to the memory that was allocated for the bigger string. Like if it was size 10 in the beginning and then on removal of 3 chars it becomes size 7. I am sure we don't need delete because we are not using "new".
>I am sure we don't need delete because we are not using "new"
That's correct.

>what happens to the memory that was allocated for the bigger string
As a general rule, every chunk of allocated memory in C/C++ (by using new or not) is deallocated entirely, so if you put an ending null character this will not alter the fact that 10 bytes will be deallocated, not 7. That's because deallocating routine doesn't inspect if a null character is present in buffer.