问题描述
- 以下字符串是怎么连接的,求解释
-
//program 6.4 joining strings
#define STDC_WANT_LIB_EXT1 1
#include
#include
int main(void)
{
char preamble[] = "the joke is:nn";
char str[][40] = {
"My dog hasn't got any nose.n",
"How does your dog smell then?n",
"My dog smells horrible.n"
};unsigned int strCount = sizeof(str)/sizeof(str[0]); unsigned int length = 0; for(unsigned int i = 0; i < strCount ; ++i) length += strnlen_s(str[i], sizeof(str[i])); char joke[length + strnlen_s(preamble, sizeof(preamble)) + 1]; if(strncpy_s(joke, sizeof(joke), preamble, sizeof(preamble))) { printf("error copying preamble to joke.n"); return 1; } for(unsigned int i = 0; i < strCount ; ++i) { if(strncat_s(joke, sizeof(joke), str[i], sizeof(str[i]))) { printf("error copying string str[%u].", i); return 2; } } printf("%s", joke); return 0;
}
这段代码到底是怎么组合字符的,搞了半天只看懂一点!
希望大神能给详细解释解释 (快到指针了,好激动)
解决方案
#define STDC_WANT_LIB_EXT1 1
#include <stdio.h>
#include <string.h>
int main(void)
{
char preamble[] = "the joke is:nn";
char str[][40] =
{
"My dog hasn't got any nose.n",
"How does your dog smell then?n",
"My dog smells horrible.n"
};
// 计算出str数组中的str个数,本程序中str值为3
unsigned int strCount = sizeof(str)/sizeof(str[0]);
unsigned int length = 0;
// strnlen_s函数返回字串的长度
for (unsigned int i = 0; i < strCount ; ++i)
length += strnlen_s(str[i], sizeof(str[i]));
// length为str数组中的字符串拼接后总长度
char joke[length + strnlen_s(preamble, sizeof(preamble)) + 1];
// 先strncpy_s函数拷贝,再strncat_s函数连接,作用区域都是joke
if (strncpy_s(joke, sizeof(joke), preamble, sizeof(preamble)))
{
printf("error copying preamble to joke.n");
return 1;
}
for (unsigned int i = 0; i < strCount ; ++i)
{
if (strncat_s(joke, sizeof(joke), str[i], sizeof(str[i])))
{
printf("error copying string str[%u].", i);
return 2;
}
}
printf("%s", joke);
return 0;
}
时间: 2024-09-14 23:38:33