Originally Posted by
Buckeye
Sorry this code is very awkward because it was designed by our university in the 80's. It's a modification of C++ and no I didn't write the add/remove functions, they are standard calls. This is the entire code for the program body of Swap_Substring.
The add/remove work with (int, char), where the integer is position in the string of text, and char is the variable that you want to use to store the character at that position. Remove's integer can only be 0<=x<|string|, while Add's integer may be 0<=x<=|string| because it allows for a character to be add at the very end.
My point is that neither Add nor Remove is within stl, thus it's a bit hard to work out exactly what they do. I discovered 3 instances of what would have been fairly horrific stack overflows, but are apparently handled within the mysterious Add and Remove functions. To cite an example, whenever t1 is smaller than t2, this code:
if(len>0){
t1.Remove(pos, ch2);
will overflow, so who even knows what's going on there. Additionally,
t1.Add(pos, ch);
will overflow at some stage because the string isn't long enough. There's something that I can only describe as dubious happening in both of those functions. I reworked it to both take from and add to the front of the string, if it's part of the brief that you work from the back, I would strongly suggest using fixed size character arrays, as adding to what is supposedly the 14th character of an empty std::string makes no sense.
I generated a vague facsimile of Add and Remove (with std::string) and took the two ints out of the Swap_Substring function. This is "proper" c++, all within the stl.
Code:
#include <iostream>
using namespace std;
void Swap_Substring(string*, string*);
char Remove(string*, unsigned);
void Add(string, unsigned, char);
int main(int argc, char** argv)
{
string t1 = "So is this one";
string t2 = "This is a non-empty string";
Swap_Substring(&t1, &t2);
cout << t1.c_str() << endl << t2.c_str() << endl;
getchar();
}
char Remove(string *str, unsigned pos)
{
char ch;
string t = *str;
ch = t[pos];
str->erase(str->begin()+pos, str->begin()+pos+1);
return ch;
}
void Add(string *str, unsigned pos, char ch)
{
str->insert(pos, 1, ch);
}
void Swap_Substring(string *t1, string *t2)
{
if(t1->length() > 0 && t2->length() > 0)
{
char ch1, ch2;
ch1 = Remove(t1, 0);
ch2 = Remove(t2, 0);
Swap_Substring(t1, t2);
Add(t1, 0, ch2);
Add(t2, 0, ch1);
}
else if(t1->length() > 0)
{
char ch1 = Remove(t1, 0);
Swap_Substring(t1, t2);
Add(t2, 0, ch1);
}
else if(t2->length() > 0)
{
char ch2 = Remove(t2, 0);
Swap_Substring(t2, t1);
Add(t1, 0, ch2);
}
}
Far from perfect and not exactly "good" code, did it fairly quickly and had to do some slightly strange things to try to ensure that the Add and Remove prototypes matched as closely as possible. Should give you something to go on at least.