2011-12-23 11 views
2

我正在尝试使用指针向后重新排序C字符串。在我的程序中,我接受字符串,然后在for循环中重新排列它。使用指针向后重新排列数组

例如,如果我输入Thomas,那么它应该使用指针返回samohT

#include <iostream> 
#include <stdio.h> 
#include <string.h> 
using namespace std; 

int main() 
{ 
    int lengthString; 

    char name[256]; 
    cout << "Please enter text: "; 
    cin.getline(name, 256); 
    cout << "Your text unscrambled: " << name << endl; 

    lengthString = strlen(name); 

    cout << "length " << lengthString << endl; 

    char* head = name; 

    char* tail = name; 

    for (int i = 0; i < lengthString; i++) 
    { 
     //swap here? 

    } 

    for (int j = lengthString - 1; j > -1; j--) 
    { 
     //swap here? 
    } 

    return 0; 
} 

我在这两个循环中遗漏了什么?

+3

for(int i = 0; i Lalaland 2011-12-23 19:40:32

+0

我需要在这里使用指针 – mystycs 2011-12-23 19:45:02

+0

你怎么需要修改就地char *? – 2011-12-23 19:54:50

回答

2
for (int i = 0; i < (lengthString/2); ++i) 
{ 
    char tempChar = name[i]; 
    name[i] = name[lengthString - i - 1]; 
    name[lengthString - i - 1] = tempChar; 
} 

编辑:

char* head = name; 
char* tail = name + lengthString - 1; 
while (head<tail) 
{ 
    char tempChar = *head; 
    *head = *tail; 
    *tail = tempChar; 
    ++head; 
    --tail; 
} 
+0

我也需要使用指针 – mystycs 2011-12-23 19:44:53

+0

它没有正确反转它。 – mystycs 2011-12-23 19:54:10

+0

@mystycs有一条线丢失。再试一次,它现在可以工作(测试它)。 – Baltram 2011-12-23 19:56:23

4

你似乎写的C和C++的混合,但你的任务需要C字符串。我会这样写。

char str[] = "Thomas"; 
size_t head = 0; 
size_t tail = strlen(str)-1; 
while (head<tail) 
{ 
    char tmp = str[head]; 
    str[head] = str[tail]; 
    str[tail] = tmp; 
    head++; 
    tail--; 
} 

您可以使用较少的变量编写此算法,但我个人发现此版本更易于阅读,理解和验证。

如果你喜欢使用指针,而不是指数,然后它看起来像这样:

char str[] = "Thomas"; 
char *head = str; 
char *tail = str + strlen(str) - 1; 
while (head<tail) 
{ 
    char tmp = *head; 
    *head = *tail; 
    *tail = tmp; 
    head++; 
    tail--; 
} 

两个版本实际上没有什么区别。

4

在C++中,你可以只使用std::reverse

例如:

std::string str = "Thomas"; 
std::reverse(str.begin(), str.end()); 
-1
#include <iostream> 
#include <sstream> 
#include <string> 
#include <algorithm> 

int main() { 
    std::cout << "Please enter text: "; 
    std::string s; 
    std::getline(std::cin, s); 
    std::cout << "Your text unscrambled: " << s << '\n'; 
    std::reverse(s.begin(), s.end()); 
    std::cout << "Your text scrambled: " << s << '\n'; 
    return 0; 
} 
+1

对不起,我意识到这不是你想要的,因为你正在处理char *。 – 2011-12-23 19:52:31

0

如果你想使用的for循环在你的程序中,你可以做这样的例子:

char reverse[256] = {0}; 
int reverseIndex = 0; 

for (int i = lengthString - 1; i >= 0; i--) 
{ 
    reverse[reverseIndex++] = name[i]; 
}