zoukankan      html  css  js  c++  java
  • 库函数(汇总)

    // 库函数
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        // 计算字符串的长度(strlen):(计算字符串中有多少个字符,注意不包括)
        // strlen的原理 : 从传入的地址开始逐个取出字符串, 每取出一个就让计数器 + 1.直到遇到为止。
    
        char str[] = "how are you"; // 定义字符数组
    
        int len = sizeof(str) / sizeof(str[0]) - 1;
        printf("%d
    ", len);
        //printf("%d
    ", strlen(str)); // 计算结果不包括 
    
        //字符串拼接(strcat)
        //原理 : 首先遍历第一个字符串, 直到遇到为止, 
        //然后取出第二个字符串中的字符, 从的位置开始添加, 添加完毕之后再在最后添加一个
        void Strcat(char *s1, char *s2)
        {
            // 找位置
            while (*s1) s1++;
    
            // 拷贝
            while(*s1++ = *s2++)
        }
    
        // 字符串拷贝(strcpy)
        // strcpy函数会将源的数据拷贝到目标中, 
        // 并且会覆盖掉目标中原有的数据,目标的容积必须能够存放拷贝的数据, 如果容积不够会报错。
    
        void Strcpy(char *s1, char *s2)
        {
            while (1)
            {
                *s1 = *s2;
                if (*s1 == '') break;
                s1++;
                s2++;
            }
    
            //while ((*s1++ = *s2++));
            
        }
    
        // 字符串比较(strcmp)
        // 原理 : 取出字符串中的每一个字符进行逐个比较, 如果发现不相等就不会继续往下比较
    
        /* strcpy 字符串赋值函数 */
        void test1() {
            char str[6] = { 0 };//表示在栈中分配了6个字节的内存空间,空间的首地址是str(数组名)
            strcpy(str, "abc");//给字符数组赋值,str[10] = "abc";
            strncpy(str, "AABBCC", sizeof(str) - 2);//只赋值前4个字符(AABB);str[6] = "AABB";
        }
        /* strcat 给一个字符串追加内容 */
        void test2() {
            char str[8] = "abc";
            strcat(str, "def"); //str[8] = "abcdef";
            strncat(str, "kkkkkk", 3);//只追加前3个字符; str[8] = "abckkk";
        }
        /* strcmp 比较字符串内容的大小 */
        void test3() {
            char *str1 = "abcd.c";
            char *str2 = "abcf.m";
            strcmp(str1, str2); //返回值为: -2 (表示 str1 < str2)
            strncmp(str1, str2, 3); //比较前3个字符的大小; 返回值为: 0 (表示 str1 == str2)
         
        }
        /* memset 内存清理函数(清空) */
        void test4() {
            char str[8] = "abcd";
            memset(str, 0, sizeof(str));//清理内存空间(开始位置, 清零, 空间大小/长度);
            strcpy(str, "ABCD");//清空后重新赋值
            printf("str = %s
    ", str);
        }
        system("pause");
        return 0;
    }
  • 相关阅读:
    CodeForces Gym 100500A A. Poetry Challenge DFS
    CDOJ 486 Good Morning 傻逼题
    CDOJ 483 Data Structure Problem DFS
    CDOJ 482 Charitable Exchange bfs
    CDOJ 481 Apparent Magnitude 水题
    Codeforces Gym 100637G G. #TheDress 暴力
    Gym 100637F F. The Pool for Lucky Ones 暴力
    Codeforces Gym 100637B B. Lunch 找规律
    Codeforces Gym 100637A A. Nano alarm-clocks 前缀和
    TC SRM 663 div2 B AABB 逆推
  • 原文地址:https://www.cnblogs.com/nothx/p/8488650.html
Copyright © 2011-2022 走看看