Hi, for example I have a string that contains the word "hello"
Now I want to remove all the "l"s from the word hello, so make it show heo.
How do I go about it in an easy way? I don't want stuff complicated. Make it as simple as possible. Thanks.
Printable View
Hi, for example I have a string that contains the word "hello"
Now I want to remove all the "l"s from the word hello, so make it show heo.
How do I go about it in an easy way? I don't want stuff complicated. Make it as simple as possible. Thanks.
I'm not going to make it for you because you don't learn by copying code from someone else.Quote:
Originally posted by trenzterra
Hi, for example I have a string that contains the word "hello"
Now I want to remove all the "l"s from the word hello, so make it show heo.
How do I go about it in an easy way? I don't want stuff complicated. Make it as simple as possible. Thanks.
How about looping through the string and copy all char's that are not equal to 'l'?
Code:J = 0
CH = 'l'
FOR I = 0 TO LENGTH(MSG)
IF MSG[I] <> CH THEN
BUF[J] = MSG[I]
J = J + 1
END IF
END FOR
BUF[J] = '\0'
I didn't think or it long enough, but maybe you can have a char * then using that pointer check out for every character and remove what you want, I think it's simple.
Well I haven't learnt about pointers... So how will char* work?
It would be better if you explained?
Imagine the characters of the string sitting next to each other in memory. I always thinks of pointers as arrows pointing at areas of memory, so you will start with 2 pointers pointing to the start of the string.Quote:
Originally posted by trenzterra
Well I haven't learnt about pointers... So how will char* work?
Now you need to move both pointers along by incrementing them (this works in a similar way to incrementing ints). Use one pointer to skip over the l's and the other to keep track of the back of the string you are building. When you finish dont forget to add the NULL to the end!
I'm not sure if this will work, no compiler at work - but it is a similar function to remove spaces from a string
Code:void stripSpace( char* string, int length )
{
char* ptr1 = string;
char* ptr2 = string;
while( *ptr2 != NULL )
{
if( *ptr2 == ' ' )
{
ptr2++; //skip l's
}
*ptr = *ptr2;
//move both pointers along 1
ptr1++;
ptr2++;
}
}
I forgot to add the '\0' to the end, sorry :(
The C++ version:
Code:#include <string>
#include <iostream>
int main(void)
{
string msg = "Hello world";
for(int i = 0; (i = msg.find('l', i)) != -1; msg.erase(i, 1)) ;
cout << msg << endl;
return 0;
}
It's even easier than that:Quote:
The C++ version:
Code:#include <string>
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string s = "Hello, world!";
cout << s << '\n';
s.erase(remove(s.begin(), s.end(), 'l'), s.end());
cout << s << '\n';
}
Thanks for the help!