在c++中反转字符串而不使用Reverse
Reverse a string in C++ without using reverse
我编写了以下代码来反转字符串而不使用<algorithm> reverse
。我写:
#include <string.h>
#include <iostream>
using namespace std;
void reverse(char *str){
int sizeStr=strlen(str);
int firstChar,lastChar,temp;
for(lastChar = (sizeStr - 1),firstChar = 0 ; lastChar>firstChar ; lastChar--, firstChar++){
temp = str[firstChar];
str[firstChar]=str[lastChar];
str[lastChar] = temp;
}
}
int main() {
char *str;
str = "myname";
reverse(str);
cout << str << endl;
return 0;
}
我在str[firstChar]=str[lastChar];
处得到段故障。请帮我找出我的错误。
注意:我声明了char str[] = "myname"
并且工作得很好。但根据你所有的解释,我们必须了解*str
和str[]
的差异。非常感谢。
不能修改常量字符串字面值。
为c++使用std::string
(感谢@chris)。使用std::swap
来交换字符。(参见c++字符串交换字符位置)
malloc
指定一个缓冲区(带有字符串的长度),strcpy
将字符串赋给它,然后对新分配的缓冲区执行reverse
。
使用std::string,您可以使用下面的方法来反转字符串
string reverse_string(string arg){
int length = arg.length();
char res[length];
for(int i = length - 1; i >= 0; i--){
res[length - (i+1)] = arg[i];
}
string result(res);
return result;
}
str的内容是常量,你应该使用char指针代替
原因是您没有为字符指针str分配内存。
#include <string.h>
#include <iostream>
using namespace std;
void reverse(char *str){
int sizeStr=strlen(str);
int firstChar,lastChar,temp;
for(lastChar = (sizeStr - 1),firstChar = 0 ; lastChar>firstChar ; lastChar--, firstChar++){
temp = str[firstChar];
str[firstChar]=str[lastChar];
str[lastChar] = temp;
}
}
int main() {
char *str;
// Here use malloc to allocate memory to the character pointer str
// Or instead of using a char pointer use a character array to initialize the string
// char *str = malloc(strlen("myname") + 1) or usr char str[10] = "myname"
str = "myname";
reverse(str);
cout << str << endl;
return 0;
}
我想你可能会用艰难的方式来解决这个问题。如果使用std::string,问题就容易多了。下面是一个更通用的c++ 1y解决方案,它将能够逆转许多不同类型的容器。容器必须覆盖[]操作符。
#include <iostream>
template <typename T>
auto rev(T &&a){
for (auto i = 0; i < a.size()/2; ++i){
std::swap(a[i], a[a.size()-1-i]);
}
return a;
}
int main(){
std::string x = "hello";
std::cout<< rev(x);
}
#include <string.h>
#include <iostream>
using namespace std;
void reverse(char *str){
int sizeStr=strlen(str);
int firstChar,lastChar,temp;
for(lastChar = (sizeStr - 1),firstChar = 0 ; lastChar>firstChar ; lastChar--, firstChar++){
temp = str[firstChar];
str[firstChar]=str[lastChar];
str[lastChar] = temp;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
char *str;
str = "myname";
char *str2 = new char [strlen(str)+1];
strcpy(str2,str);
reverse(str2);
cout << str2 << endl;
delete [] str2;
str2 = NULL;
cout << str << endl;
return 0;
}
#include <string.h>
#include <iostream>
void myreverse(std::string &s) {
size_t begin = 0, end = s.length();
while ((begin != end) && (begin != --end))
std::swap(s[begin++], s[end]);
}
int main() {
const char *str = "myname";
std::cout << str << std::endl;
std::string newstr(str);
myreverse(newstr);
std::cout << newstr << std::endl;
return 0;
}