2011-12-23 39 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]; 
}