粗暴,干就完了----徐晓冬似的C语言自学笔记---字符数组相关技术

  • 字符串拼接函数

          strcat()

  • 字符串----作为很多编程语言的鼻祖C语言,没有字符串类型,取而代之的字符数组,很多数组在声明的时候会给定数组长度,然而我们却可以这样写

          char mywords[] = "you and me hold breath count to 3";

  • 计算字符串(实际上是字符数组)长度 strlen()
#include <stdio.h>
#include <string.h>
void main()
{
   printf("喜欢陈培昌");
   getchar();
   char mywords[] = "you and me hold breath count to 3";
   printf(strcat(mywords," "));
   printf("字符数组的长度是%d",strlen(mywords));
   printf(" ");
}

 输出结果:

  •  遍历输出数组元素

有其他语言编程习惯的朋友,习惯在循环条件中声明循环变量i的类型,but 在C语言,I'm deeply sorry这就出错了

c语言的习惯是先声明循环变量,然后再循环条件中使用定义好的循环变量

#include <stdio.h>
#include <string.h>
void main()
{
   char mywords[] = "劲儿弟弟和昌仔在擂台实战,汗水,昏黄的灯光,青年搏击运动员荷尔蒙,鞋柜里散发的脚味,姑娘们和老外的香水味,混杂在一起,越发的让一切迷乱起来";
   int i=0; 
   for(i=0;i<strlen(mywords);i++)
    {
      printf("%c",mywords[i]);
    }
   printf("
");
}
  •  数组元素逆序
#include <stdio.h>
#include <string.h>
void main()
{
   char mywords[] = {"don't break myheart"};
   char reversearray[sizeof(mywords)] = {0};
   int arraysize;
   arraysize = sizeof(mywords);
   printf("%d",arraysize);
   printf("
");
   int i=0; 
   for(i=0;i<arraysize;i++)
    {
        reversearray[arraysize-i-2]=mywords[i];
    }
   printf(reversearray);
   printf("
");
}

注意,字符数组变量值的部分一定要用{}包裹,声明的空数组一定要用{0}包裹,否则将无法得到实验结果

中文字符串的处理需要另外讨论

输出结果:

  •  宽字符----可以处理中文的类型

注意,下列上机环境为centos7,windows下写法略有不同,主要体现在本地化函数setlocate上面,如果你参照的出版物无法得到预期结果,可能和操作系统有关

#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <locale.h>
void main()
{
   setlocale(LC_ALL, "zh_CN.UTF-8");
   wchar_t mywords = L''; #注意,单一字符不用加方括号[]
   wprintf(L
"%lc ",mywords);#单一字符输出格式为lc wchar_t iwant[] = L"想用脸碰一下劲儿弟弟的毛儿扎头"; wprintf(L"%ls ",iwant);#字符串输出格式为ls }

输出结果:

 

原文地址:https://www.cnblogs.com/saintdingspage/p/11213295.html