- Classes
- Fall14 CS31
- Week 6 Classwork
Example One: csReverse
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void csReverse (char c[]) {
// [!] Save the cstring size
int size = strlen(c);
// [!] We'll flip each character from the
// front with the ones at the end, moving our
// iterator inwards...
// What should be our terminating condition?
for (int i = 0; i < size / 2; i++) {
// Save c[i] into a temp variable
char holder = c[i];
// [!] Set c[i] to the one on the end
// (remember we're iterating inwards)
c[i] = c[size - i - 1];
// [!] Then set that equal to the holder
c[size - i - 1] = holder;
}
}
int main () {
char c1[] = "testz";
char c2[] = "!";
char c3[] = "";
csReverse(c1);
csReverse(c2);
csReverse(c3);
cout << c1 << endl;
cout << c2 << endl;
cout << c3 << endl;
}
Example Two: multiCStringAppend
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
const int MAX_CSTRING_SIZE = 20 + 1;
/*
* Appends cstring toAppend to each cstring in target
*/
void multiCStringAppend (char target[][MAX_CSTRING_SIZE], char toAppend[], int n) {
// Simply iterate through all n elements in
// the target...
for (int i = 0; i < n; i++) {
// ...and append toAppend to each element
strcat(target[i], toAppend);
}
}
int main () {
char c1[][MAX_CSTRING_SIZE] =
{
"test",
"my",
"function!"
};
multiCStringAppend(c1, " yay!", 3);
for (int i = 0; i < 3; i++) {
cout << c1[i] << endl;
}
}