用c++输入三个字符串,通过指针读取各个字符串的子串(子串是指字符串中连续的一小部分),把它们合并成一个新字符串
时间: 2023-05-29 10:01:23 浏览: 118
```c
#include <stdio.h>
#include <string.h>
#define MAXSIZE 50
void getSubstr(char *str, int start, int end, char *substr);
//获取字符串str中 [start, end) 区间内的子串
int main(void)
{
char str1[MAXSIZE], str2[MAXSIZE], str3[MAXSIZE];
char *p1, *p2, *p3;
char substr1[MAXSIZE], substr2[MAXSIZE], substr3[MAXSIZE];
char newstr[MAXSIZE*3+1];
printf("Enter string 1: ");
fgets(str1, MAXSIZE, stdin);
printf("Enter string 2: ");
fgets(str2, MAXSIZE, stdin);
printf("Enter string 3: ");
fgets(str3, MAXSIZE, stdin);
//获取各个字符串的子串
getSubstr(str1, 0, strlen(str1)-1, substr1); //整个字符串作为子串
getSubstr(str2, 1, strlen(str2)-2, substr2); //去掉末尾的换行符
getSubstr(str3, 3, 6, substr3);
//合并成新字符串
p1 = substr1;
p2 = substr2;
p3 = substr3;
while(*p1 != '\0')
{
*newstr++ = *p1++;
}
while(*p2 != '\0')
{
*newstr++ = *p2++;
}
while(*p3 != '\0')
{
*newstr++ = *p3++;
}
*newstr = '\0'; //注意加上字符串结束符
printf("New string: %s", newstr-MAXSIZE*3); //输出时回到newstr的起始位置
return 0;
}
void getSubstr(char *str, int start, int end, char *substr)
{
int i;
for(i=start; i<end; i++)
{
substr[i-start] = str[i];
}
substr[i-start] = '\0';
}
```
阅读全文