2014-12-07 314 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的5個字符複製到STR2起始於字符串STR1的索引0,那麼串STR1的5字符複製到STR2起始於字符串1的索引1,依此類推。例如,第一個str2應該是「this」。第二個str2 =「他我」。第三個str2「是」。請幫助球員,謝謝如何將字符串的一部分複製到另一個字符串中?

回答

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

    //... 
} 

這裏開始是一個更完整的示例

#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

它的工作, 謝謝! – stanlopfer 2014-12-07 17:53:58

+0

@stanlopfer查看我更新的帖子。:) – 2014-12-07 18:03:06

1

只需將您的偏移量添加到strncpy調用的str1參數。例如:

strncpy(str2,str1 + 1,5); 

將複製5個字節到從STR1 STR2索引1

-1

你正在嘗試做什麼r要注意你的字符串索引和指針偏移量。這並不困難,但是如果您嘗試讀取/寫入越界,則會立即輸入未定義的行爲。下面的示例提供了顯示它發生的輸出,以便您可以直觀地看到該過程。

我是不是你的確切目的或者你打算做str3,但無論如何,下面的原理適用完全清楚:

#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' 
相關問題