C语言基础总结 ( 三 )----------字符串总结

😊字符串处理函数
#include <string.h> // 字符串数组头文件
    // puts输出函数
    char str[20] = "zyp";
    printf("who loves %s\n", str); // 不会自动换行
    puts(str);
    puts("gj"); // 不能进行格式化输出
   
    // gets输入函数
    char str2[15];
    gets(str2); // 使用scanf时不能有空格,gets中间可以有空格
    puts(str2);
   
    // strcat   字符串连接函数
    // 返回的是前面的字符串的地址,保存在前面的字符串数组中
    strcat(str, str2);
    puts(str);
    printf("连接后的字符串为%s\n", str);
   
    // strcpy   字符串拷贝函数
    // strcpy(str1, str2)   把字符串2拷贝到字符串1中,字符串1中的内容被覆盖
                    str1的长度 >= str2的长度
    strcpy(str, str2);
    puts(str);
   
    // strcmp   字符串比较函数
    char str3[] = "ac";
    char str4[] = "fun";
    printf("%d\n", strcmp(str3, str4));
   
    // strlen   计算字符串的长度
    char str5[] = "德玛西亚";   // 一个汉字默认是 utf-8 编码,占用3个字节
    printf("%lu\n", strlen(str5));
 
 
😊单词首字母大写统计单词个数
    // 首先定义一个字符串数组
    char str[100];
    // 定义变量count统计单词的个数
    int count = 0;
    int isWord = 1; // 用来判别是不是单词
    // 输入字符串
    gets(str);
    // 循环判断字符是不是\0
    for (int i = 0; str[i] != '\0'; i++) {
        // 再判断是不是单词
        if (str[i] == ' ') {
            isWord = 1; // 等于空格说明这是一个单词的开始
        }else if (isWord == 1){
            str[i] = str[i] - 32;
            count++;
            isWord = 0; // 循环得到一个单词后就把isword归0
        }
    }
     printf("%d\n", count);
    puts(str);
posted @ 2015-03-21 13:23  丶貌似文艺小青年  阅读(157)  评论(0编辑  收藏  举报