题目要求编写一个函数来处理字符串,在全部字符之间加入空格。
总时间限制: 1000ms 内存限制: 65536kB
编写一个函数,函数的参数是一个字符串指针,函数的功能完成在字符串中每隔一个字符插入一个空格。在主函数打印变化后的字符串。 注意:要在同一个字符串中操作,不要再定义一个字符串。
一个字符串指针。
变化后的字符串。
test
test ab
test
t e s t
t e s t a b
t e s t
题目要求不要再定义一个字符串来处理,我们首先就需要把原来的字符串定义得长一点,然后加入空格实际上就是使得原有字符的下标乘以2,从后向前操作就不会影响到其他字符了。
#include <iostream>
using namespace std;
void insert0(char* cstr) {
int i;
for (i = 19; i >= 0; --i) {
cstr[i * 2] = cstr[i];
}
for (i = 1; i < 40; i += 2) {
cstr[i] = ' ';
}
}
int main() {
char strin[40];
while (cin.getline(strin, 40, '\n')) {
insert0(strin);
cout << strin << endl;
}
return 0;
}
2909.cpp 代码长度:315B 内存:128kB 时间:2ms 通过率:95% 最小内存:128kB 最短时间:0ms
函数应当传递字符串收地址,由于原始输入可能存在空格,所以需要使用cin.getline来读取一行,第二参数是读取的长度,第三个参数是结尾标志字符。
有任何的改进意见欢迎大家在微信平台公众号主页面留言或者发表issue。