在 C++ 中反转字符串

Reversing string in C++

在下面的部分字符串交换代码

 end = &str[len - 1];

我不理解寻址部分。当我在没有寻址部分的情况下执行此操作时,它仍然会运行,但会警告我 "a values of type char cannot be assigned to identity of type char"。这是完整的代码:

    #include<iostream>
    #include<cstring>
    using namespace std;

int main()
{
    char str[] = "This is a test";
    char *start, *end; 
    int len;
    int t; 

    cout << "Original " << str << "\n";
    len = strlen(str);
    start = str;
    end = str[len - 1];  

//this reverses the string
    while (start < end) { 

        t = *start;  
        *start = *end; 
        *end = t; 

        start++; 
        end--; 

    }
    cout << "Reversed" << str << "\n";
    system("PAUSE");
    return 0;
}

I am not understanding the addressing part.

给出

char str[] = "This is a test";
char *start, *end; 
len = strlen(str);

那么end是指向char的指针,而

end = &str[len - 1]; // `end` points to the last character (before the `[=11=]`)

您必须使用 &(地址)运算符,因为 end 是指针,因此必须将其分配给某物的地址(此处为字符串最后一个字符的地址) .

When I do it without the addressing part it still runs

我认为不会 - 你应该遇到编译错误

end = str[len - 1]; // invalid conversion from ‘char’ to ‘char*’

你应该知道end的类型是char*,但是str[len-1]的类型是char,所以你需要把类型str[n-1]改成char*, 所以你需要 &str[len-1].

但是如果你使用string,会有一个简单的方法:

使用 STL 中的 std::reverse 方法:

std::reverse(str.begin(), str.end()); //str应该是字符串类型

您必须包含 "algorithm" 库 #include。

也许这可以帮助

void reverse (char word[])
{
   int left = 0;
   int right = strlen(word) - 1;

   while (left < right)
   {
      char temp = word[left];
      word[left] = word[right];
      word[right] = temp;
      left++;
      right--;
   }
   cout << word;

}

我希望这能给你灵感。