gpt4 book ai didi

c - 如何连接字符和字符串/How to make char to string

转载 作者:行者123 更新时间:2023-12-03 11:33:10 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define MAX_SIZE 20

void main()
{
int i, j;
char *str1, *str2, *str3, *str_mid;
bool **lcs1, **lcs2;
int len1, len2, len3, len_mid;
char *ch = (char*)malloc(sizeof(char) * 3);


str1 = (char*)malloc(sizeof(char)*MAX_SIZE); //applicatian
str2 = (char*)malloc(sizeof(char)*MAX_SIZE); //apiasn
str3 = (char*)malloc(sizeof(char)*MAX_SIZE); //apun
str_mid = (char*)malloc(sizeof(char)*MAX_SIZE); //apn

str_mid = "";

scanf("%s", str1);
scanf("%s", str2);
scanf("%s", str3);

len1 = strlen(str1);
len2 = strlen(str2);
len3 = strlen(str3);

//str2, str3 ->str_mid (lcs1)
lcs1 = (bool**)malloc(sizeof(bool*)*(len3 + 1));
for (i = 0; i < len3 + 1; i++)
lcs1[i] = (bool*)malloc(sizeof(bool)*(len2 + 1));

for (i = 0; i < len3 + 1; i++)
for (j = 0; j < len2 + 1; j++)
lcs1[i][j] = false;

for (i = 1; i < len3 + 1; i++)
for (j = 1; j < len2 + 1; j++)
if (str3[i-1] == str2[j-1])
lcs1[i][j] = true;

for (i = 1; i < len3 + 1; i++)
{
for (j = 1; j < len2 + 1; j++)
if (lcs1[i][j])
{
//<--- error
ch = str3[i - 1];
strcat(str_mid, ch);
//--->
break;
}
}

//printf("%s", str_mid);
//str_mid, str1 (lcs2)

}

在<---错误--->部分,
我想连接 str3[i-1]str_mid 但是,str3[i-1] 是字符类型。
因此,使临时字符串为 ch 并执行concatenate
但是,发生了访问错误。
如何将字符转换为字符串,或者,如何连接字符和字符串?

最佳答案

只要 MAX_SIZE 足够大,str_mid 就能容纳额外的字符,您就可以使用 strcat() 和一个复合文字(对于 C99 或更高版本):

strcat(str_mid, (char[2]){ str3[i - 1], '\0' });

请注意,在您的代码中,str3[i - 1] 是一个 char,而您已将 ch 声明为指向 字符

关于c - 如何连接字符和字符串/How to make char to string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41195141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com