程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 代碼-以下字符串是怎麼連接的,求解釋

代碼-以下字符串是怎麼連接的,求解釋

編輯:編程綜合問答
以下字符串是怎麼連接的,求解釋

//program 6.4 joining strings
#define STDC_WANT_LIB_EXT1 1
#include
#include
int main(void)
{
char preamble[] = "the joke is:\n\n";
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:\n\n";
    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;
} 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved