c - c中的字符串连接问题
问题描述
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int x,y;
char s1[30],s2[30];
printf("Enter string 1:");
scanf("%s",s1);
printf("Enter string 2:");
scanf("%s",s2);
x=sizeof(s1),y=sizeof(s2);
char cs1[x+y+1];
char cs2[x+y+1];
for (int i = 0; i < x; i++)
{
cs1[i]=s1[i];
}
for (int i =x; i < (x+y); i++)
{
cs1[i]=s2[i];
}
for (int i = 0; i < (y); i++)
{
cs2[i]=s2[i];
}
for(int i=y;i<(x+y);i++)
{
cs2[i]=s1[i];
}
cs1[x+y]='\0';
cs2[x+y]='\0';
printf("string 1+string 2 is:%s",cs1);
printf("\nstring 2+ string 1 :%s",cs2);
return 0;
}
我试图在不使用内置函数的情况下连接两个字符串,你能指出错误吗?这是给字符串,因为它们是我的意思是说它正在打印 s1 字符串代替 cs1 和 s2 代替 cs2
解决方案
这些任务:
x=sizeof(s1),y=sizeof(s2);
没有意义,因为分配的值不代表输入字符串的长度。
你需要写:
#include <string.h>
//...
size_t x,y;
char s1[30],s2[30];
printf("Enter string 1:");
scanf("%s",s1);
printf("Enter string 2:");
scanf("%s",s2);
x = strlen(s1), y = strlen(s2);
//...
这些 for 循环:
for (int i =x; i < (x+y); i++)
{
cs1[i]=s2[i];
}
//...
for(int i=y;i<(x+y);i++)
{
cs2[i]=s1[i];
}
不正确。你需要写:
for ( size_t i = 0; i < y; i++)
{
cs1[i + x] = s2[i];
}
//...
for( size_t i = 0; i < x; i++)
{
cs2[i + y ] = s1[i];
}
推荐阅读
- react-native - 错误:无法从 `./debugger-ui/debuggerWorker.cff11639.js` 解析模块:
- iis - IIS 中的重写/重定向规则导致斜杠
- php - MySql 不能使用错误安装 testlink using PHP 7.x from Xampp
- node.js - 如何使用 Node.js 创建与 DynamoDB 表的简单连接?
- prometheus - 如何标记警报以了解 Prometheus 中的目标对象?
- react-native - 是否可以使用 expo-sharing 共享文本消息和图像?
- java - Spring Data JPA 规范,如何在唯一的 sql 请求中获取 @JoinColumn 数据
- angular - 如何修复不存在的 Reactive Forms 错误
- c# - Html.CheckBoxFor 无法正常运行并生成不同的 html 然后镜像副本
- json - JSONPath 返回 JProperty 而不是 JObject