zoukankan      html  css  js  c++  java
  • C语言中常用的string.h的字符函数

    strcmp

    字符串比较函数

    原型: int strcmp(char *str1, char *str2); 

    例子: if(strcmp(buf1,buf2)>0) printf("buffer 1 is greater than buffer 2. "); 

    str1>str2,返回值 > 0(一般返回1),两串相等,返回0
     

    strlen

    字符串长度函数

    原型: int strlen(const char *s); 

    例子: char *buf1="haha"; len=strlen(buf1); //len=4 

    strstr

    查找字符串str2在str1第一次出现的位置

    原型:  char *strstr(char *str1, char *str2); 

    例子:

    char *str1 = "She is prrety", *str2 = "he", *ptr;
    ptr = strstr(str1, str2);
    printf("The substring is: %s
    ", ptr);
    printf("The position is:%d
    ",ptr-str1);
    
    //输出:
    //The substring is: he is prrety
    //The position is:1

    strcpy

    拷贝字符串

    原型: char *strcpy(char *destin, char *source); 

    例子:

    char string[10];
    char *str1 = "abcdefghi";
    strcpy(string, str1);
       
    printf("%s
    ", string);
    
    //输出:
    //abcdefghi

    strncpy 

    strncpy(string, str1,3);//string=str1的前三个字符

    strcat

    字符串拼接函数

    原型: char *strcat(char *destin, char *source); 

    例子:

    char str[25];
    char *str1 ="I am", *str2 = " Lucy.";
    strcpy(str,str1); //先复制str1的内容
    strcat(str,str2); //再接上str2的内容
    printf("%s
    ", str);
    //输出
    //I am Lucy.

    要注意的是,strcat的第一个参数只能是str这样定义的数组,不能是指针str1

    strchr

    查找字符在字符串的位置

    原型:  char *strchr(char *str, char c); 

    例子:

    char string[15]="BUPT";
    char *ptr, c = 'U';
    ptr = strchr(string, c);
    if (ptr)
    printf("The character %c is at position: %d
    ", c, ptr-string);
    else
    printf("The character was not found
    ");
    //输出:
    //The character %c is at position: 1

      

  • 相关阅读:
    git 常用命令总结
    Activiti(工作流)如何关联业务表
    常见数据结构复杂度
    linux 启动 oracle数据库
    word2vec 入门(三)模型介绍
    数组中出现次数超过一半的数字 -java
    word2vec 入门(二)使用教程篇
    word2vec 入门基础(一)
    Stackoverflow上人气最旺的10个Java问题(转ImportNew)
    leetcode 326. Power of Three(不用循环或递归)
  • 原文地址:https://www.cnblogs.com/flipped/p/5005627.html
Copyright © 2011-2022 走看看