C.char字符串的拼接和const char*的转换

C里没有String类型

要用char[]来代替String的职能

上代码:

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 int main(void)
 5 {
 6     const char *p1;
 7     char str1[] = "hello";
 8     char str2[] = " world";
 9     char newStr[50] = "";
10     strcat(newStr, "good,"); //直接把字符串添加到newStr
11     strcat(newStr, str1);    //str1添(追)加到newStr
12     strcat(newStr, str2);    //str2添(追)加到newStr
13     p1 = newStr;             //char可以直接赋值给const char*
14     printf("p1: %s\n", p1);
15     printf("p1.length(err): %d\n", sizeof(p1)); //这个获取的长度并不是真实字符串长度
16     printf("p1.length: %d\n", getLength(p1));
17     printf("str1.length: %d \n", sizeof(str1)); //(含字符串尾部的结束符\0,所以长度要加1)
18     printf("str2.length: %d\n", sizeof(str2));
19     printf("newStr.length: %d \n", sizeof(newStr)); //(按实际定义的数组长度)
20

运行结果:

p1: good,hello world
p1.length(err): 8
p1.length: 16
str1.length: 6
str2.length: 7
newStr.length: 50

 

posted @ 2020-09-02 10:35  幻河  阅读(2610)  评论(0编辑  收藏  举报