programing

C에서 2개의 스트링을 연결하려면 어떻게 해야 하나요?

prostudy 2022. 7. 30. 11:34
반응형

C에서 2개의 스트링을 연결하려면 어떻게 해야 하나요?

2개의 스트링을 추가하려면 어떻게 해야 하나요?

는 는 i i는노노 i i i i i.name = "derp" + "herp";에러가 발생했습니다.

식에는 정수 또는 열거 형식이 있어야 합니다.

C는 일부 다른 언어에서 사용할 수 있는 문자열을 지원하지 않습니다.은 C의 입니다.char첫 번째 늘 문자로 끝납니다.C 에 c c c c c c c c c c c c 。

strcat2년 전하다다음 기능을 사용하여 수행할 수 있습니다.

#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;
}

스트링으로 많은 작업을 할 계획이라면 스트링을 지원하는 다른 언어를 사용하는 것이 좋을 수 있습니다.

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);
  }
}

스트링당 10KB로 부족할 경우 크기에 0을 추가하면 됩니다.스택 메모리는 스코프의 마지막에 해방됩니다.

#include <stdio.h>

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

문자열 연결

C의 임의의 2개의 스트링을 접속하는 방법은 적어도3가지입니다.-

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;
}

이와 같은 문자열 리터럴은 C에 추가할 수 없습니다.문자열 리터럴1 + 문자열 리터럴2 + 바이트 크기의 버퍼를 생성하여 대응하는 리터럴을 해당 버퍼에 복사하고 null 끝임을 확인해야 합니다.또는 다음과 같은 라이브러리 기능을 사용할 수 있습니다.strcat.

#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);
}

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;
}

자세한 내용은 malloc, freeasprintf를 참조하십시오.

를 사용해 주세요.strcat또는 그 이상입니다.strncat. 구글에서 검색(키워드는 "연결 중").

C에서는 일반 퍼스트 클래스 개체로서 문자열이 실제로 없습니다.문자 배열로 관리해야 합니다.즉, 어레이를 관리하는 방법을 결정해야 합니다.한 가지 방법은 예를 들어 스택에 배치되는 정규 변수입니다.또 다른 방법은 다음과 같이 동적으로 할당하는 것입니다.malloc.

정렬이 완료되면 어레이의 내용을 다른 어레이로 복사하여 두 문자열을 연결할 수 있습니다.strcpy또는strcat.

그러나 C는 컴파일 시에 알려진 문자열인 문자열 리터럴(string literal)이라는 개념을 가지고 있습니다.사용할 경우 읽기 전용 메모리에 배치되는 문자 배열이 됩니다.단, 2개의 문자열 리터럴을 서로 옆에 쓰는 것으로 연결할 수 있습니다."foo" "bar"문자열 리터럴 "foobar"가 생성됩니다.

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;
}

언급URL : https://stackoverflow.com/questions/8465006/how-do-i-concatenate-two-strings-in-c

반응형