如何将一定长度的字符串放入c中的二维数组
how to get certain length string into 2d array in c
我正在尝试制作一个接受字符串(例如:"Hello I am on Whosebug")并以给定宽度打印出所述字符串的函数。所以如果宽度是 10
你好我是
在 stackov 上
erflow
`void Left(char* words, int width)
{
int length = strlen(words);
int divisions = length / width; //How many lines there will be
if (divisions%length!=0) divisions+=1; //If some spillover
printf("%d = divisions \n", divisions);
char output[divisions][width];
int i;
int temp;
for(i=0; i < divisions; i++)
{
strncpy(output[i][temp], words, width);
output[i][width] = '[=10=]';
temp+= width;
}
}`
这是我目前编写的函数。因此输出将有与新行一样多的行,每行具有与宽度给定的一样多的文本。我想我用错了 strncpy 但我不确定。有帮助吗?
字符串的宽度不包括字符串终止符,因此output[i][width] = '[=10=]';
将终止符写出边界。
您正朝着正确的方向前进,但首先需要认识到一些事情:
char output[divisions][width];
是一个字符串数组,其中包含 'divisions' 个字符字符串,每个字符串的大小为 'width'。并且 strncpy 将 'char *' 作为目标缓冲区的参数。 http://man7.org/linux/man-pages/man3/strcpy.3.html
因此要复制您的数据,您需要提供如下目标字符串-
strncpy(&output[i], words, width);
这会将 'width' 长度的数据从字符串 'words' 复制到字符串 'output[i]'。
现在要让您的函数起作用,您必须在每次迭代后向前移动 'words' 指针。例如:
前 10 个字节 - "Hello I am" 从 'words' 复制到 'output[0]' 所以你需要在下一次迭代中从第 11 个字节开始处理,所以只需添加
words += width;
printf("%s \n", output[i]);
此外,如前一个答案所述,不要忘记字符串终止符和其他边界条件。
我正在尝试制作一个接受字符串(例如:"Hello I am on Whosebug")并以给定宽度打印出所述字符串的函数。所以如果宽度是 10
你好我是
在 stackov 上
erflow
`void Left(char* words, int width)
{
int length = strlen(words);
int divisions = length / width; //How many lines there will be
if (divisions%length!=0) divisions+=1; //If some spillover
printf("%d = divisions \n", divisions);
char output[divisions][width];
int i;
int temp;
for(i=0; i < divisions; i++)
{
strncpy(output[i][temp], words, width);
output[i][width] = '[=10=]';
temp+= width;
}
}`
这是我目前编写的函数。因此输出将有与新行一样多的行,每行具有与宽度给定的一样多的文本。我想我用错了 strncpy 但我不确定。有帮助吗?
字符串的宽度不包括字符串终止符,因此output[i][width] = '[=10=]';
将终止符写出边界。
您正朝着正确的方向前进,但首先需要认识到一些事情:
char output[divisions][width];
是一个字符串数组,其中包含 'divisions' 个字符字符串,每个字符串的大小为 'width'。并且 strncpy 将 'char *' 作为目标缓冲区的参数。 http://man7.org/linux/man-pages/man3/strcpy.3.html
因此要复制您的数据,您需要提供如下目标字符串-
strncpy(&output[i], words, width);
这会将 'width' 长度的数据从字符串 'words' 复制到字符串 'output[i]'。
现在要让您的函数起作用,您必须在每次迭代后向前移动 'words' 指针。例如: 前 10 个字节 - "Hello I am" 从 'words' 复制到 'output[0]' 所以你需要在下一次迭代中从第 11 个字节开始处理,所以只需添加
words += width;
printf("%s \n", output[i]);
此外,如前一个答案所述,不要忘记字符串终止符和其他边界条件。