2014-12-07 4 views
1
#include <stdio.h> 
#include <string.h> 
void main(int ac, char *av[]) 
{ 
    char str1[] = "this is a test"; 
    char str2[20]; 
     char str3[30]; 
    strncpy(str2,str1,5); 

} 

문자열 str1의 인덱스 0부터 시작하여 문자열 str1의 5 문자를 str2로 복사 한 다음 문자열 1의 인덱스 5에서부터 문자 str1의 5 문자를 str2로 복사하는 식으로합니다. 예를 들어 첫 번째 str2는 "this"여야합니다. 두 번째 str2 = "his i". 세 번째 str2는 "is"입니다. 얘들 아, 도와주세요.문자열의 일부를 다른 문자열로 복사하는 방법은 무엇입니까?

답변

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

int main() 
{ 
    char str1[] = "this is a test"; 
    char str2[20]; 
    char str3[30]; 

    strncpy(str2, str1, 5); 
    str2[5] = '\0'; 
    strncpy(str3, str1 + 1, 5); 
    str3[5] = '\0'; 

    //... 
} 

로되어 시작 STR1에서 STR2에 5 바이트를 복사한다

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

int main() 
{ 
    char str1[] = "this is a test"; 
    char str2[sizeof(str1) - 5][6]; 
    const size_t N = sizeof(str1) - 5; 
    size_t i; 

    for (i = 0; i < N; i++) 
    { 
     strncpy(str2[i], str1 + i, 5); 
     str2[i][5] = '\0'; 
    } 

    for (i = 0; i < N; i++) 
    { 
     puts(str2[i]); 
    } 

    return 0; 
} 

출력

this 
his i 
is is 
s is 
is a 
is a 
s a t 
a te 
a tes 
test 
+0

이 일

나는 당신의 정확한 목적이나 당신이 str3 함께 할, 그러나에 관계없이, 다음과 같은 원칙을 적용하도록에 완전히 명확하지 않았다 , 고맙습니다! – stanlopfer

+0

@stanlopfer 업데이트 된 게시물보기. :) –

1

호출의 str1 인수에 오프셋을 추가하기 만하면됩니다. 예를 들어

strncpy(str2,str1 + 1,5); 

은보다 완전한 예를 지수 1. 여기

-1

시도하려는 작업 r 문자열 인덱스와 포인터 오프셋에주의를 기울여야합니다. 어렵지는 않지만 경계를 읽거나 쓰려고하면 즉시 정의되지 않은 동작을 입력합니다. 아래 예제는 프로세스를 시각적으로 볼 수 있도록 수행되는 작업을 보여주는 출력을 제공합니다.

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

int main() 
{ 
    char str1[] = "this is a test"; 
    char str2[20] = {0};      /* always initialize variables */ 
    // char str3[30] = {0}; 

    size_t i = 0; 
    char p = 0;         /* temp char for output routine */ 

    for (i = 0; i < strlen (str1) - 4; i++)  /* loop through all chars in 1 */ 
    {           /* strlen(str1) (- 5 + 1) = - 4 */ 
     strncpy (str2+i, str1+i, 5);   /* copy from str1[i] to str2[i] */ 

     /* all code that follows is just for output */ 
     p = *(str1 + i + 5);     /* save char at str1[i]   */ 
     *(str1 + i + 5) = 0;     /* (temp) null-terminate at i */ 
     /* print substring and resulting str2 */ 
     printf (" str1-copied: '%s' to str2[%zd], str2: '%s'\n", str1+i, i, str2); 
     *(str1 + i + 5) = p;     /* restor original char   */   
    } 

    return 0; 
} 

출력 :

$ ./bin/strpartcpy 
str1-copied: 'this ' to str2[0], str2: 'this ' 
str1-copied: 'his i' to str2[1], str2: 'this i' 
str1-copied: 'is is' to str2[2], str2: 'this is' 
str1-copied: 's is ' to str2[3], str2: 'this is ' 
str1-copied: ' is a' to str2[4], str2: 'this is a' 
str1-copied: 'is a ' to str2[5], str2: 'this is a ' 
str1-copied: 's a t' to str2[6], str2: 'this is a t' 
str1-copied: ' a te' to str2[7], str2: 'this is a te' 
str1-copied: 'a tes' to str2[8], str2: 'this is a tes' 
str1-copied: ' test' to str2[9], str2: 'this is a test' 
관련 문제