Reversing in 2 pairs means for example: we have a string "helloworld" we need to output in a way that it returns "ehllworodl". We can see that each pair it reverse and concatenated for output.
1 Answer
Try this
string input = "helloworld";
string output = "";
for (int i = 0; i < input.Length - 1; i += 2)
{
output += input[i + 1];
output += input[i];
}
3 Comments
Vahlkron
This only works if your character count is even. If your string happened to be "helloworl", the "l" would be left out.
M.kazem Akhgary
@Vahlkron it will definitely works. because of the condition
i < input.Length - 1. the -1 means leave the last character. "helloworl".Length will be 9. therefore i will be 8 and its end of the loop. because 8 < 9 - 1 would be false. please dont downvote a correct answerWDS
OP asks for a program to reverse a string by pairs of characters, jdweng provides exactly that. A string of odd count letters was undefined in the question, so I think it's fine that it be undefined in the answer also. Maybe the OP should move it alone as though it were paired with a blank or maybe he could throw an exception. But it was not up to jdweng to guess.