2014-12-07 164 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' 
相关问题