我strcat()用来连接两个字符串,如:
#include <string.h>
#include <stdio.h>
int main(int argc, char *args[])
{
char *str1; // "456"
char *str2; // "123"
strcat(str1,str2);
printf("%s",str1);
}
Run Code Online (Sandbox Code Playgroud)
我得到:
456123
Run Code Online (Sandbox Code Playgroud)
但是我需要在第一个字符串开头的第二个字符串,例如:
123456
Run Code Online (Sandbox Code Playgroud)
我该怎么做 ?
执行strcat(str2,str1);,切换参数。但是,您将在中得到结果字符串str2,str1如果您确实想str1在程序中进一步使用它,可以将其设置为。
但是,您需要适当注意中的可用内存空间str2。
如果要更改str1,请执行此操作
char *tmp = strdup(str1);
strcpy(str1, str2); //Put str2 or anyother string that you want at the begining
strcat(str1, tmp); //concatenate previous str1
...
free(tmp); //free the memory
Run Code Online (Sandbox Code Playgroud)