目录
Language: C++
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string.h>
using namespace std;
int main() {
char str[1001];
int case_num;
cin >> case_num;
getchar();
while (case_num--) {
cin.getline(str, 1000);
int len = strlen(str);
int i = 0, j = 0;
char tmp;
/* 注意这里有等于,处理'\0'的情况 */
while (j <= len) {
/* 遇到子串结尾 */
if (str[j] == ' ' || str[j ] == '\0') {
/* 字符串反转 */
int a = i, b = j - 1;
while (a < b) {
tmp = str[a];
str[a] = str[b];
str[b] = tmp;
a++;
b--;
}
/* 子串指针头移至下一节 */
i = j + 1;
}
/* 子串指针尾后移 */
j++;
}
cout << str << endl;
}
return 0;
}
Analysis
- 遇到输入字符串包含空格,想到用cin.getline,前面就要配一个getchar;
- 整体上看就是字符串反转算法的应用,类似的题直接想到要用两个指针:头指针、尾指针