颠倒字符串的顺序
Reversing the sequence of a string
一个相当简单的程序,试图在C++中反转以null结尾的字符串中的字符,但似乎出了问题。
#include <iostream>
using namespace std;
void reverse(char*);
int main(){
char *str;
cout<< "Please enter a string, no spaces please..";
cin >> str;
//reverse(str);
}
void reverse(char *str){
char temp;
size_t len = strlen(str);
for (size_t i = 0; i < len/2; i--)
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
获取以下错误
Bus error: 10
感谢您的帮助。
-
在使用
char *str = new char[25];
之前为str
分配内存 -
在
reverse
函数中用于for
循环增量i
for (size_t i = 0; i < len/2; i++ )
-
使用
delete [] str ;
后取消分配内存
您正在递减迭代器i
,而不是递增它
#include <algorithm>
#include <cstring>
void reverse(char* const str)
{
unsigned long const len = strlen(str);
for(unsigned long i = 0; i < len >> 1; i++)
std::swap(str[len - i - 1], str[i]);
}
#include <algorithm>
#include <string>
#include <iostream>
#include <cstring>
int main() {
// You can't read something to nowhere.
// String will be holded in static array.
char str[1024];
// To keep it as null terminated string after
// writing of inputed string: `std::cin` don't
// write null character after writing of data.
memset(str, 0, 1024);
std::cin >> str;
// If you do reversing of strings in C++,
// you shouldn't use hand written loops:
std::reverse(str, str + strlen(str));
std::cout << str << std::endl;
}
试试这个修改后的代码版本:
#include <iostream>
#include <cstring>
using namespace std;
void reverse(char*);
int main(){
char str[1024]; // buffer of 1024 chars
cout<< "Please enter a string, no spaces please..";
cin >> str;
reverse(str);
cout << "nReversed: " << str;
}
void reverse(char *str){
char temp;
size_t len = strlen(str);
for (size_t i = 0; i < len/2; i++) // loop until half of the user input
{
temp = str[i];
str[i] = str[len-i-1];
str[len-i-1] = temp;
}
}
我只是添加了字符char str[1024];
的数组来存储用户输入。。并将循环更改为:for (size_t i = 0; i < len/2; i++)
但是,您必须非常小心地使用上面的代码。。如果输入的大小小于数组的固定大小,则它可以正常工作。
相关文章:
- 按字母顺序对字符串中的字母进行排序,而无需使用内置的 sort()
- 按字母顺序对C++问题中的子字符串索引进行分区
- 提高从排序字符串中获取字母顺序的顺序复杂性
- 字符串变量顺序
- 高效的字符串截断算法,按顺序删除相等的前缀和后缀
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- C++按字母顺序排列的字符串数组
- 如何在 c++ 中按字母顺序排列数组中的字符串?
- C++ 按数值对元组<字符串、浮点数>然后按字典顺序排序的向量
- 如何根据长度然后字母顺序对数组字符串进行排序?
- C 在向量的向量中按字母顺序排序字符串
- 将字符串值分配给Char数组以相反的顺序进行循环
- 检索字符串的第一个字符,并在C++中按字母顺序进行比较
- 将字符指针按顺序存储在 map 中 std::map<char*, int> mymap。将其存储为字符或字符串不是一个选项
- 添加字符串和文字,顺序如何影响是否可以正确添加字符串
- 我不知道如何创建一个以数字/字母顺序打印出我的整数或字符串的程序
- 按字母顺序对字符串数组进行排序C++
- 在 C++ 中使用链表按字母顺序对字符串进行排序
- 如何将整数向量转换为 2 位十六进制并按顺序添加到 c 字符串?
- 链接列表并按字母顺序插入字符串