Okay, so I need some help getting my string to swap around.
Here is the overall code of what I am trying to do, but I can't just move the string around. I started off trying to convert it to characters but the majority of replies said to just use the std::swap function, however I am really lost in using this...
My overall goal is to permute a string, which can be specified to a certain section of the string. I am new to C++, I am just unsure how to use C++ methods/functions in order to achieve this.
(there is also a main.cc and Permutation h. but its only for defining variables, skeletal code basically)
All help appreciated, I shall check back here in about 2 hours.
UPDATED CODE)
#include <iostream> // for cout
#include <cstdio> // for printf()
#include <sstream> // for stringstream
#include <stdio.h>
#include <string.h>
#include "Permutation.h"
using namespace std;
Permutation::Permutation() {
/* nothing needed in the constructor */
}
void Permutation::permute(const string& str) {
string stringnew = str;
int j;
int low = 0;
int high = str.length();
cout << stringnew << endl;
for (j = 0; j <= high; j++) {
string strtemp = stringnew[j];
std::swap((strtemp + low), (strtemp + j));
permute(str, low + 1, high);
std::swap(str[j + low], str[j + j]);
}
}
void Permutation::permute(const string& str, int low, int high) {
// int j;
// if (low == high) {
// cout << str << endl;
// } else {
// for (j = low; j <= high; j++) {
// std::swap(str[j + low], str[j + j]);
// permute(str, low + 1, high);
// std::swap(str[j + low], str[j + j]);
// }
// }
}
You must work through the class interface. You cannot get a writeable character array from a std::string
.
What you can do is use the array subscript operator and access it as str[i]
. You can also use iterators.
The reason for this is that prior to C++03, std::string
was not required to be a character array. It could be discontinuous. At least one implementation used a std::deque
style "array of pointers to arrays" backing store, which gave it fast insert, prepend and delete-from-the-middle abilities.
Also, from an Object Oriented programming design perspective, it is Not Nice to reach into an object's guts and rearrange them.
Just for fun because I wanted a break from work, some code that messes with a string using array subscripts:
#include <cctype>
#include <string>
#include <iostream>
void uc(std::string &s)
{
size_t i;
const size_t len = s.length();
for(i=0; i<len; ++i) {
s[i] = toupper(s[i]);
}
}
void mix(std::string &s)
{
size_t i;
const size_t len = s.length();
for(i=1; i<len/2+1; ++i) {
std::swap(s[i-1], s[len-i]);
}
}
int main()
{
std::string s("Test String");
uc(s);
std::cout << s << std::endl;
mix(s);
std::cout << s << std::endl;
return 0;
}