need help with arrays

S

shemgwapo

Guest
im practically new to c++ coding and i have this little problem..

how do you swap chars? i mean lets say it goes something like this

cout<<"enter word";
cin>>word;
cout<<"pos";
cin>>pos;

lets say you enter a word "Hello"
and you enter a numer "2" in pos.

my problem is since i entered the number "2"
i want the output to be "llohe"
and if i enter in the pos 3
the output would be "lohel"

anyone could give me a code on how to do it? pls? thanks in advance..
 
Yeah, it depends on what type "word" is. If it's a C-string (that is, a char*), you'd use the C string manipulation functions in string.h (strcpy and such). If it's a string class from C++, you'd use the string class's member functions.
 
Here is an algorithm:

1. create a new string, <result>, with same size as <word>
2. copy into <result> all characters in <word> from index <pos> to the last character in <word>
3. copy into <result> all characters in <word> from index 0 to <pos> minus 1

Here is a quick way to do it:

Code:
std::string result;

for(int i = pos ; i < word.size() ; i++)
	result += word[i];

for(int i = 0 ; i < pos ; i++)
	result += word[i];

Or:

Code:
int len = strlen(word);
char* szResult = new char[len + 1]; // dont forget to delete!!

strncpy(szResult, word[pos], len - pos);
strncat(szResult, word, pos);
 
Back
Top