Need some advice
Apr 5, 2018 at 8:38am UTC
I got this 2 functions that should erase everything in brackets,but when i started to test it i forgot that someone might put brakets in the wrong places...
So the question is,can i imrpove my code or should i start from scratch?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#include <iostream>
#include <string>
using namespace std;
string eraseSubStringInBrackets(string&);
char eraseSubStringInBrackets(char * ps);
int main()
{
char *str = new char [255];
cout << "Enter string > " ;
cin.getline(str, 255);
cout << endl;
string str2(str);
cout << "Original C-string > " << str << endl << endl;
cout << "Original String > " << str2 << endl << endl;
eraseSubStringInBrackets(str);
cout << "New C-string > " << str << endl << endl;
eraseSubStringInBrackets(str2);
cout << "New String > " << str2 << endl << endl;
return 0;
}
string eraseSubStringInBrackets(string& s)
{
int left = s.find_first_of("(" );
int right = s.find_first_of(")" );
while (left != string::npos)
{
s.erase(left, (right - left) + 1);
left = s.find_first_of("(" , left + 1);
right = s.find_first_of(")" , right + 1);
}
return s;
}
char eraseSubStringInBrackets(char * ps)
{
char *p1 = strchr(ps, '(' );
char *p2 = strchr(ps, ')' );
for (int i = 0; ps[i] != NULL; i++)
{
p1 = strchr(ps, '(' );
p2 = strchr(ps, ')' );
if (p1 && p2)
{
memmove(p1, p2 + 1, strlen(p2) + 1);
}
}
return 0;
}
Apr 5, 2018 at 8:56am UTC
Sounds like you want to begin with something simple like
1 2 3 4 5 6 7 8
if (left < right)
{
// go ahead and do the erasing
}
else
{
// the string was bad - the closing bracket was before the opening bracket
}
and then go on to handle more complex cases like
hjg)grehu)ghe(grnej()(()())ghrt)gh(
Apr 5, 2018 at 11:44am UTC
It did work in the string function,now im having problems with the char array.
Topic archived. No new replies allowed.