squeeze function

S

sara

Hi,

I have implemented the following method to remove all the occurences
of c from string s.

void squeeze(char* s, char c)
{
char string[]="";
strcpy(string,s);

int src=0;
int dst=0;

while(string[src]!='\0')
{
while (string[src]!='c')
{
src++;
if (string[src]!='\0')
dst++;
}

if (string[src]=='\0')
break;

while(string[src]=='c')
src++;
string[dst]=string[src];
}

string[dst+1]=0;

return;
}

How can I change the fucntion to return the string variable? If I make
the function 'char[] squeeze(char* s, char c)' it does not compile and
if I make it 'char* squeeze(char* s, char c)' I got some weird error.
Also, is it possible to write the functon more efficiently?
 
T

Tim Love

sara said:
I have implemented the following method to remove all the occurences
of c from string s.

Also, is it possible to write the functon more efficiently?
You can use this approach


#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
string s="spaces in text";
cout << s << endl;
s.erase(remove(s.begin(), s.end(), ' ' ), s.end() ) ;
cout << s << endl;
}
 
S

sara

You can use this approach

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
string s="spaces in text";
   cout << s << endl;
   s.erase(remove(s.begin(), s.end(), ' ' ), s.end() ) ;  
   cout << s << endl;

}

thanks but I want to implement in C not C++
 
S

SG

void squeeze(char* s, char c)
{
    char string[]="";
    strcpy(string,s);

What do you think is the exact type of string and what is the type's
interface, its semantics? Hint: If s points to a non-empty character
string this code will result in a buffer overflow error (undefined
behaviour).
How can I change the fucntion to return the string variable?
[...]
If I make
the function 'char[] squeeze(char* s, char c)' it does not compile and
if I make it 'char* squeeze(char* s, char c)' I got some weird error.

The fact that you ask these questions indicates that you don't know
how arrays and pointers work in C and C++. Check your favorite
tutorial and/or book and brush up these C/C++ basics.
thanks but I want to implement in C not C++

Then, you picked the wrong group.

Cheers,
SG
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,836
Latest member
BuyBlissBitesCBD

Latest Threads

Top