反向字符串C ++使用字符数组 [英] Reverse String C++ using char array
问题描述
我写了一个简单的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;
}
}
现在这种方法是行不通的,并且我得到空字符串作为程序执行后的结果。
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?
推荐答案
给定一个的char * str中
,的sizeof(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 ::互换()
在C ++中,如果要交换两个变量的内容,使用 的std ::互换
,而不是临时变量。
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]);
请注意如何更清楚那是。
Note how much clearer that is.
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));
}
在测试,这两个产生 dlrow东海生日贺
上的输入的Hello World
。
When tested, both of these produce dlrow olleh
on an input of hello world
.
这篇关于反向字符串C ++使用字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!