【发布时间】:2020-03-28 11:53:22
【问题描述】:
编写并测试您自己的函数 char * funct (char * str, int x) 反转(除了位置 n 处的字符)字符串 str 并返回修改后的 str 作为结果。函数func的使用可以是:
这是主要的:
#include <iostream>
#include <cstring>
using namespace std;
char* funct(char *str, int x);
int main() {
char str1 [] = "Hello cpp";
cout << str1 << endl; // Hello cpp
cout << funct (str, 1) << endl; // pepC ollH // the character at position 1 ('e') stays in place
return 0;
}
这是我的功能:
char* funct(char *str, int x) {
int counter = 0;
do {
counter++;
str++;
} while (*str);
str--;
char *wskTmp = str;
for (int i = 0; i < counter ; i++) {
*wskTmp = *str;
str--;
wskTmp++;
}
*wskTmp = '\0';
wskTmp = wskTmp - counter;
for (int i = 0; i < counter - x -1; i++) {
wskTmp++;
}
char tmp;
for (int i = 0; i < counter-3; i++) {
tmp = *(wskTmp - 1);
*(wskTmp - 1) = *wskTmp;
*wskTmp = tmp;
wskTmp--;
}
return str;
}
输出:
你好 Cpp
你好 CppepC ollH
应该是:
你好 Cpp
pepC ollH
为什么它在“pepC ollH”之前给我 Hello Cp?
【问题讨论】:
-
我试图返回 wskTmp,它给了我 epC ollH。 “e”之前的“p”在哪里???????
-
wskTmp 设置为字符串的末尾,然后您进一步增加它,这会导致错误。你想完成什么?