题目:读入一行文本,包含若干个单词(以空格间隔,或文本结束)。将其中的以A开头的单词与以N结尾的单词,用头尾交换的办法予以置换。
实例:
输入:“AM I OLDER THAN YOU”
输出:“THAN I OLDER AM YOU”
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
void exchange(char *in, char *out)
{
int s1, s2, e1, e2; // s1记录以A开头的单词首字母,e1为其尾字母;s2e2同理对应N
int i = 0, k = 0;
char *p;
while (*(in + i) != '\0')
{
// 定位好对应的位置的首尾字母,保存在s1;s2;e1;e2
if (*(in + i) == 'A' && (i == 0 || *(in + i - 1) == ' '))
{
s1 = i;
while (*(in + i) != ' ')
{
i++;
}
e1 = i - 1;
}
if (*(in + i) == 'N' && (*(in + i + 1) == ' ' || *(in + i + 1) == '\0'))
{
e2 = i;
while (*(in + i) != ' ')
{
i--;
}
s2 = i + 1;
i = e2;
}
i++;
}
i = 0;
p = out;
while (*(in + i) != '\0')
{
if (i == s1)
{
for (int j = 0; j < e2 - s2 + 1; j++)
{
*(p + k++) = *(in + s2 + j);
}
i = e1;
}
else if (i == s2)
{
for (int j = 0; j < e1 - s1 + 1; j++)
{
*(p + k++) = *(in + s1 + j);
}
i = e2;
}
else
{
*(p + k++) = *(in + i);
}
i++;
}
*(p + k) = '\0';
}
int main(int argc, char const *argv[])
{
char a[100] = "AM I OLDER THAN YOU";
char b[100];
puts(a);
exchange(a, b);
puts(b);
return 0;
}
思路参考博客链接:
https://blog.youkuaiyun.com/weixin_42780429/article/details/104875092