使用字符数组反转字符串 C++ [英] Reverse String C++ using char array

查看:42
本文介绍了使用字符数组反转字符串 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的 C++ 程序来反转字符串.我在字符数组中存储一个字符串.要反转字符串,我使用相同的字符数组和临时变量来交换数组的字符.

I wrote a simple C++ program to reverse a string. I store a string in character array. To reverse a string I am using same character array and temp variable to swap the characters of an array.

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

void reverseChar(char* str);

char str[50],rstr[50];
int i,n;

int main()
{
    cout<<"Please Enter the String: ";
    cin.getline(str,50);
    reverseChar(str);
    cout<<str;
    return 0;
}

void reverseChar(char* str)
{
    for(i=0;i<sizeof(str)/2;i++)
    {
        char temp=str[i];
        str[i]=str[sizeof(str)-i-1];
        str[sizeof(str)-i-1]=temp;
    }
}

现在这个方法不起作用,我在程序执行后得到 NULL String 作为结果.

Now this method is not working and, I am getting the NULL String as result after the program execution.

所以我想知道为什么我不能等同于字符数组,为什么这个程序不起作用.我可以使用什么解决方案或技巧来使相同的程序工作?

So I want to know why I can't equate character array, why wouldn't this program work. And what is the solution or trick that I can use to make the same program work?

推荐答案

sizeof(str) 不符合您的预期.

给定一个 char *strsizeof(str) 不会给你那个字符串的长度.相反,它会给你一个指针占用的字节数.您可能正在寻找 strlen() 代替.

sizeof(str) does not do what you expect.

Given a char *str, sizeof(str) will not give you the length of that string. Instead, it will give you the number of bytes that a pointer occupies. You are probably looking for strlen() instead.

如果我们解决了这个问题,我们会:

If we fixed that, we would have:

for(i=0;i<strlen(str)/2;i++)
{
    char temp=str[i];
    str[i]=str[strlen(str)-i-1];
    str[strlen(str)-i-1]=temp;
}

这是C++,使用std::swap()

在C++中,如果要交换两个变量的内容,使用std::swap 而不是临时变量.

This is C++, use std::swap()

In C++, if you want to swap the contents of two variables, use std::swap instead of the temporary variable.

所以代替:

char temp=str[i];
str[i]=str[strlen(str)-i-1];
str[strlen(str)-i-1]=temp;

你会写:

swap(str[i], str[sizeof(str) - i - 1]);

注意这有多清楚.

std::reverse(str, str + strlen(str));

全局变量

如果不需要,将变量设为全局是非常糟糕的做法.特别是,我指的是 i 关于这个.

如果我要编写此函数,它将类似于以下两种实现之一:

If I was to write this function, it would look like one of the two following implementations:

void reverseChar(char* str) {
    const size_t len = strlen(str);

    for(size_t i=0; i<len/2; i++)
        swap(str[i], str[len-i-1]);
}

void reverseChar(char* str) {
    std::reverse(str, str + strlen(str));
}

经过测试,这两种方法都会在 hello world 的输入上产生 dlrow olleh.

When tested, both of these produce dlrow olleh on an input of hello world.

这篇关于使用字符数组反转字符串 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆