C 中的字符连接

标签 c string pointers

我想用C来做,用Java可以实现如下

String str = "hello";
System.out.println(str + 'a');

我写了以下内容。 1. 不起作用 2. 有没有更简单的方法在 C 中做到这一点,在 java 中只需一行即可实现。

#include <stdio.h>

char* charcat(char str[], char c);

int main(void)
{
 char str[] = "hello";
 printf("%s\n",charcat(str,'a'));
}

char* charcat(char str[], char c)
{
 char newstr[] = {c,'\0'};
 char temp[20];

 strcpy(temp,str);
 strcat(temp,newstr);

 return temp;
}

编辑: 我根据 ameyCU 的回复进行了编辑。

char* charcat(char str[], char c);

int main(void)
{
 char str[] = "hello";

 printf("%s\n",charcat(str,'a'));
}

char* charcat(char str[], char c)
{
 char* temp;
 char newstr[] = {c,'\0'};

 temp = malloc((strlen(str) + 1)* sizeof(char));
 strcpy(temp,str);
 return strcat(temp,newstr);
}

编辑2:

char* charcat(char str[], char c);

int main(void)
{
 char str[] = "hello";
 char temp[20];

 strcpy(temp,str);
 printf("%s\n",charcat(temp,'a'));
}

char* charcat(char str[], char c)
{
 char newstr[] = {c,'\0'};
 return strcat(str,newstr);
}

最佳答案

我认为你想做的是:

char* charcat(char str[], char c)
{
 char newstr[] = {c,'\0'};
 char *temp=(char *)malloc((strlen(str)+1+1)*sizeof(char));

 strcpy(temp,str);
 strcat(temp,newstr);

 return temp;
}

确保你 free() 了指针。

关于C 中的字符连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31761005/

相关文章:

c - 如何声明一个函数来接受指向整数数组的指针

java - java中比较两个字符串,如何打印等于单词

c - C 中的不完整类型 'struct' 错误

c - 对 'WinMain' 的 undefined reference [错误] ld 返回 1 退出状态,将矩阵作为函数中的参数传递

c++ - 增加内存映射文件的大小

c - "assignment discards ' const 非常量指针上的 ' qualifier"错误

c - C 中的列表和字符串问题

string - 如何将 String 转换为 UnsafePointer<UInt8> 和长度

实例化时使用 new 关键字的 C++ 指针和引用

c - MASM64,Visual studio 2015 C 程序,具有单独文件中的汇编功能