簡體   English   中英

如何在C中連接兩個字符串?

[英]How do I concatenate two strings in C?

如何添加兩個字符串?

我試過name = "derp" + "herp"; ,但我得到了一個錯誤:

表達式必須具有整數或枚舉類型

C 不支持某些其他語言所具有的字符串。 C 中的字符串只是指向以第一個空字符結尾的char數組的指針。 C 中沒有字符串連接運算符。

使用strcat連接兩個字符串。 您可以使用以下功能來做到這一點:

#include <stdlib.h>
#include <string.h>

char* concat(const char *s1, const char *s2)
{
    char *result = malloc(strlen(s1) + strlen(s2) + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    strcpy(result, s1);
    strcat(result, s2);
    return result;
}

這不是執行此操作的最快方法,但您現在不必擔心。 請注意,該函數將堆分配的內存塊返回給調用者並傳遞該內存的所有權。 調用者有責任在不再需要時free內存。

像這樣調用函數:

char* s = concat("derp", "herp");
// do things with s
free(s); // deallocate the string

如果您碰巧被性能困擾,那么您應該避免重復掃描輸入緩沖區以尋找空終止符。

char* concat(const char *s1, const char *s2)
{
    const size_t len1 = strlen(s1);
    const size_t len2 = strlen(s2);
    char *result = malloc(len1 + len2 + 1); // +1 for the null-terminator
    // in real code you would check for errors in malloc here
    memcpy(result, s1, len1);
    memcpy(result + len1, s2, len2 + 1); // +1 to copy the null-terminator
    return result;
}

如果您打算使用字符串進行大量工作,那么最好使用對字符串具有一流支持的其他語言。

#include <stdio.h>

int main(){
    char name[] =  "derp" "herp";
    printf("\"%s\"\n", name);//"derpherp"
    return 0;
}

David Heffernan 在他的回答中解釋了這個問題,我編寫了改進的代碼。 見下文。

通用函數

我們可以編寫一個有用的可變參數函數來連接任意數量的字符串:

#include <stdlib.h>       // calloc
#include <stdarg.h>       // va_*
#include <string.h>       // strlen, strcpy

char* concat(int count, ...)
{
    va_list ap;
    int i;

    // Find required length to store merged string
    int len = 1; // room for NULL
    va_start(ap, count);
    for(i=0 ; i<count ; i++)
        len += strlen(va_arg(ap, char*));
    va_end(ap);

    // Allocate memory to concat strings
    char *merged = calloc(sizeof(char),len);
    int null_pos = 0;

    // Actually concatenate strings
    va_start(ap, count);
    for(i=0 ; i<count ; i++)
    {
        char *s = va_arg(ap, char*);
        strcpy(merged+null_pos, s);
        null_pos += strlen(s);
    }
    va_end(ap);

    return merged;
}

用法

#include <stdio.h>        // printf

void println(char *line)
{
    printf("%s\n", line);
}

int main(int argc, char* argv[])
{
    char *str;

    str = concat(0);             println(str); free(str);
    str = concat(1,"a");         println(str); free(str);
    str = concat(2,"a","b");     println(str); free(str);
    str = concat(3,"a","b","c"); println(str); free(str);

    return 0;
}

輸出:

  // Empty line
a
ab
abc

清理

請注意,您應該在不需要時釋放分配的內存以避免內存泄漏:

char *str = concat(2,"a","b");
println(str);
free(str);

我假設你需要它來做一次性的事情。 我假設您是 PC 開發人員。

使用堆棧,盧克。 到處使用它。 永遠不要將 malloc / free 用於小分配。

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

#define STR_SIZE 10000

int main()
{
  char s1[] = "oppa";
  char s2[] = "gangnam";
  char s3[] = "style";

  {
    char result[STR_SIZE] = {0};
    snprintf(result, sizeof(result), "%s %s %s", s1, s2, s3);
    printf("%s\n", result);
  }
}

如果每個字符串 10 KB 不夠,請在大小上加一個零,不要打擾,無論如何,它們都會在作用域的末尾釋放它們的堆棧內存。

您應該使用strcat或更好的strncat 谷歌它(關鍵字是“連接”)。

您不能像在 C 中那樣添加字符串文字。您必須創建一個大小為字符串文字 1 + 字符串文字 2 + 一個字節的緩沖區,用於空終止字符,並將相應的文字復制到該緩沖區,並確保它以空終止. 或者您可以使用諸如strcat類的庫函數。

沒有 GNU 擴展:

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

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    res = malloc(strlen(str1) + strlen(str2) + 1);
    if (!res) {
        fprintf(stderr, "malloc() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    strcpy(res, str1);
    strcat(res, str2);

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

或者使用 GNU 擴展:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    if (-1 == asprintf(&res, "%s%s", str1, str2)) {
        fprintf(stderr, "asprintf() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

有關更多詳細信息,請參閱mallocfreeasprintf

#include <string.h>
#include <stdio.h>
int main()
{
   int a,l;
   char str[50],str1[50],str3[100];
   printf("\nEnter a string: ");
   scanf("%s",str);
   str3[0]='\0';
   printf("\nEnter the string which you want to concat with string one: ");
   scanf("%s",str1);
   strcat(str3,str);
   strcat(str3,str1);
   printf("\nThe string is %s\n",str3);
}

連接字符串

可以通過至少 3 種方式連接 C 中的任意兩個字符串:-

1) 通過將字符串 2 復制到字符串 1 的末尾

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX];
  int i,j=0;
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  for(i=strlen(str1);str2[j]!='\0';i++)  //Copying string 2 to the end of string 1
  {
     str1[i]=str2[j];
     j++;
  }
  str1[i]='\0';
  printf("\nConcatenated string: ");
  puts(str1);
  return 0;
}

2) 通過將字符串 1 和字符串 2 復制到字符串 3

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX],str3[MAX];
  int i,j=0,count=0;
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  for(i=0;str1[i]!='\0';i++)          //Copying string 1 to string 3
  {
    str3[i]=str1[i];
    count++;
  }
  for(i=count;str2[j]!='\0';i++)     //Copying string 2 to the end of string 3
  {
    str3[i]=str2[j];
    j++;
  }
  str3[i]='\0';
  printf("\nConcatenated string : ");
  puts(str3);
  return 0;
}

3) 通過使用 strcat() 函數

#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
  char str1[MAX],str2[MAX];
  printf("Input string 1: ");
  gets(str1);
  printf("\nInput string 2: ");
  gets(str2);
  strcat(str1,str2);                    //strcat() function
  printf("\nConcatenated string : ");
  puts(str1);
  return 0;
}

使用 memcpy

char *str1="hello";
char *str2=" world";
char *str3;

str3=(char *) malloc (11 *sizeof(char));
memcpy(str3,str1,5);
memcpy(str3+strlen(str1),str2,6);

printf("%s + %s = %s",str1,str2,str3);
free(str3);

我在這里使用asprintf

示例代碼:

char* fileTypeToStr(mode_t mode) {
    char * fileStrBuf = NULL;
    asprintf(&fileStrBuf, "%s", "");

    bool isFifo = (bool)S_ISFIFO(mode);
    if (isFifo){
        asprintf(&fileStrBuf, "%s %s,", fileStrBuf, "FIFO");
    }

...

    bool isSocket = (bool)S_ISSOCK(mode);
    if (isSocket){
        asprintf(&fileStrBuf, "%s %s,", fileStrBuf, "Socket");
    }

    return fileStrBuf;
}

在 C 中,您實際上沒有字符串作為通用的一流對象。 您必須將它們作為字符數組進行管理,這意味着您必須確定您希望如何管理您的數組。 一種方法是將普通變量,例如放在堆棧上。 另一種方法是使用malloc動態分配它們。

排序后,您可以將一個數組的內容復制到另一個數組,以使用strcpystrcat連接兩個字符串。

話雖如此,C 確實有“字符串文字”的概念,它們是編譯時已知的字符串。 使用時,它們將一個字符數組放置在只讀存儲器中。 但是,可以通過將兩個字符串文字並排書寫來連接它們,如"foo" "bar" ,這將創建字符串文字 "foobar"。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM