编一程序,将两个字符串连接起来,不要用strcat函数
#include <stdio.h>
#include "stdlib.h"
#include <string.h>
int main(){
char *ch1[100];
char *ch2 [100];
printf("请输入第一个字符串,按回车键结束:");
int i=0,j=0;
for( i;(char c=getchar())!='\n';i++){
ch1[i]=(char *)malloc(sizeof(char));
*ch1[i]=c;
}*(ch1[i])='\0';
printf("请输入第二个字符串,按回车键结束:");
for(j;(char c=getchar())!='\n';j++){
ch2[j]=(char *)malloc(sizeof(char));
*ch2[j]=c;
}*(ch2[j])='\0';
int a=i+j-1;
char ch_blend[a];
for(int k=0;k<a;k++){
if(k<i-1) ch_blend[k]=*(ch1[k]);
else ch_blend[k]=*(ch2[k-i]);
}ch_blend[a-1]='\0';
for(int s=0;s<i;s++) free(ch1[s]);
for(int s=0;s<j;s++) free(ch2[s]);
return 0;
}
1
#include <stdio.h> void func(const char *s1, const char *s2) { char result[200]; // 存储拼接后的字符串 int i = 0, j = 0; // 复制第一个字符串到 result while (s1[i] != '\0') { result[i] = s1[i]; i++; } // 复制第二个字符串到 result while (s2[j] != '\0') { result[i] = s2[j]; i++; j++; } result[i] = '\0'; // 结束字符串 // 输出拼接后的字符串 printf("拼接结果: %s\n", result); } // 测试函数 int main() { const char *str1 = "Hello, "; const char *str2 = "World!"; func(str1, str2); return 0; }
#include <stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #define N 10 int main(void) { char word[20] = "hello",word1[10] = "world";
for (int i = 0; i < 2 * N; i++) {// \0妙用 if (word[i] == '\0') { int j; for ( j = 0; word1[j]!='\0'; j++) { word[i] = word1[j]; i++; } break; } } printf("新字符串%s\n",word); return 0; } /*法二: int main(void) { char word[30] = "hello", word1[10] = "world"; // 增大 word 数组的大小以容纳拼接后的字符串 int i = 0, j = 0, k = 0; // i 用于遍历 word,j 用于遍历 word1,k 用于记录 word 中下一个空闲位置
// 找到 word 字符串的末尾 while (word[i] != '\0') { i++; } k = i; // 更新 k 为 word 中\0位置 // 将 word1 的内容复制到 word 的末尾 while (word1[j] != '\0') { word[k] = word1[j]; k++; j++; }
// 在拼接后的字符串末尾添加空字符 word[k] = '\0';
printf("新字符串%s\n", word);
return 0; } */
【答案解析】
直接将s2中的...
用户登录可进行刷题及查看答案
直接将s2中的字符逐个拷贝到s1的末尾即可,用户需要保证s1中能存的下s2中的字符
#include<stdio.h> int main() { char s1[100] = {0}; char s2[50] = { 0 }; int index1 = 0, index2 = 0; printf("请输入字符串s1:"); scanf("%s", s1); printf("请输入字符串s2:"); scanf("%s", s2); printf("将s2拼接在s1之后: "); // 1. 找到s1的末尾 while ('\0' != s1[index1]) index1++; // 2. 将s2中的字符逐个往s1之后拼接 while (s1[index1++] = s2[index2++]); printf("%s\n", s1); return 0; }
登录后提交答案