I have the following code in c# which reverses a string:
char[] charArray = s.ToCharArray();
int len = s.Length - 1;
for (int i = 0; i < len; i++, len--)
{
charArray[i] ^= charArray[len];
charArray[len] ^= charArray[i];
charArray[i] ^= charArray[len];
}
return new string(charArray);
I am trying to convert it to C++ as an intellectual exercise more than anything. Here is what I have so far:
void main(void)
{
char* str = "testing";
char* result;
int len;
len = strlen(str);
if (len <= 12)
{
result = new char[strlen(str)];
for (int i = 0; i < len; i++, len--)
{
result[i] ^= str[len];
result[len] ^= str[i];
result[i] ^= str[len];
}
}
else{
std::reverse(str, &str[strlen(str)]);
}
cout << endl << result << endl;
// cleanup
str = NULL;
result = NULL;
}
In .Net if the string is <= 12 (I think it’s twelve) xor is faster than array reverse. Source – Sam Saffron I am basically trying to see if it still holds up in C++.
The string comes out in a weird format (════╣¥¿ë²²² to be precise).
Any ideas?
Note: I know the else statement doesn’t work, I’ll figure that bit out after 😉
Note 2: I am probably doing this completely wrong, so feel free to point absolutely anything out
Update
Thanks to everyone that has participated. I haven’t played with c++ in a fair few years (and it shows) and thought it would be quiet easy to convert but obviously not. Think it’s best I abandon this idea. Thanks again
A few things:
Should be
lenbecause you’ve already calculated the length ofstr, and+ 1to make room for the NUL terminator.Secondly, you need to copy the string into
resultbefore operating on it, because otherwise your array is full of garbage otherwise:Thirdly,
Is wrong for two reasons: one, because you can’t modify string literals, and two, because you should be using
result:But if you do that, you also need to copy
strintoresultfirst.And lastly, setting a pointer to
NULLdoes not deallocate the memory it points to. You have toNote that for this to work even when the
elseis taken (and thereforeresultis not made to point to allocated memory), you need to doAll the above applies if you’re sure you want to use C-strings. Once you get the hang of pointers, you can graduate to
std::string: