c - 使用while循环在C中反转字符串
问题描述
这段代码基本上应该采用一个字符串,例如它是“abc de fgh”,输出应该是
cba
ed
hgf
此处显示的代码确实将字符串放入一行,但不会反转它们。我在想出那部分以及如何在方法中使用我的论点中的 char* 时遇到了麻烦。在正确方向上的任何帮助都会很棒!
void stringReverse(char* s){
char* i = 0;
char* j = strlen(s)-1;
//in order to swap the characters s[i] and s[j] make a temp
char* temp;
while(i < j){
temp = i;
i = j;
j = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
解决方案
您的代码似乎混合了使用索引(如0
or strlen(s)-1
)或使用指针的概念。即使在评论中,您也写了“交换字符s[i]
和s[j]
”,但您将i
和声明j
为char*
变量。
第二个错误是您交换了指针值,而不是指针指向的字符。
您应该决定是否要使用指针或索引来访问字符。
使用指针的解决方案:
void stringReverse(char* s){
//in order to swap the characters s[i] and s[j] make a temp
char temp;
char* i = s;
/* according to the standard, the behavior is undefined if the result
* would be one before the first array element, so we cannot rely on
* char* j = s + strlen(s) - 1;
* to work correct. */
char* j = s + strlen(s);
if(j > i) j--; // subtract only if defined by the C standard.
while(i < j){
temp = *i;
*i = *j;
*j = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
使用索引的解决方案:
void stringReverse(char* s){
size_t i = 0;
size_t j = strlen(s)-1;
//in order to swap the characters s[i] and s[j] make a temp
char temp;
while(i < j){
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
如果启用了足够的警告,编译器应该警告原始源代码中的一些问题。我建议始终启用尽可能多的警告。
推荐阅读
- caddy - 如何在 Caddyfile 中重定向保留路径的某些部分?
- salesforce - Apex DML 无法识别 SOQL 所做的变量
- excel - 在 Excel 中使用 IF 获取一系列值
- r - 如何更改ggplot中的x轴标签
- vue.js - Vuex mapActions、mapGetters 等...在同一个调用中混合命名空间和非命名空间操作/getters/mutations/state?
- python - 我的朋友在尝试在 Lynda 上学习 Python 教程时,在 Visual Studio 中继续收到错误消息。关于如何解决这个问题的任何建议?
- python - pandas 分组和聚合
- react-native - 在博览会中接收通知时播放不同的声音
- angularjs - angular 6中是否有类似于angularJs form.firstname.$active的元素
- json - 将多行 json 字符串插入 helm 模板以进行 base64 编码