#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中,然后将字符串str1的5个字符从string1的索引1开始复制到str2,依此类推。例如,第一个str2应为“this”。第二个str2 =“他的我”。第三个str2“是”。请帮帮忙,谢谢
答案 0 :(得分:1)
只需将您的偏移量添加到str1
调用的strncpy
参数即可。例如:
strncpy(str2,str1 + 1,5);
将从索引1开始从str1复制5个字节到str2。
答案 1 :(得分: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
答案 2 :(得分:0)
您尝试做的事情需要特别注意字符串索引和指针偏移。这并不困难,但如果您尝试读取/写出界限,则会立即输入未定义的行为。下面的示例提供了显示其发生情况的输出,以便您可以直观地看到该过程。
我并不完全清楚您的确切目的或您打算如何使用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'