字符串函数

来源:互联网 发布:淘宝联盟怎么得佣金 编辑:程序博客网 时间:2024/06/13 01:21

课程笔记

单字符输入输出

putchar()和getchar()

int putchar(int c);

EOF表示写失败

int getchar(void)


头文件 string.h

strlen( const char *s)

返回s的字符串长度(不包括结尾的0)


int strlen(const char* s){    int cnt;    //计数器    int idx;    //下标索引     while(s[idx] != '\0' ){        idx++;        cnt++;    }    return cnt;}int main (int argc, char const *argc[]){    char line[] = "Hello";    printf("strlen=%lu\n",strlen(line));    printf("sizeof=%lu\n",sizeof(line));}


输出结果为5, 6

可做的优化:计数器与下标索引合一


strcmp(const char *s1, char *s2)


strcpy(const char *s1, char *s2)


strcat(const char *s1, char *s2)


strchr(const char *s1, char *s2)

#include #include #include int main(int argc, char const *argv[]){    char s[] = "Hello";    char *p = strchr(s, 'l');   //find string after the first 'l'    printf("%s\n",p);        return 0;   }//output llo#include #include #include int main(int argc, char const *argv[]){    char s[] = "Hello";    char *p = strchr(s, 'l');   //find string after the first 'l'    p = strchr(p+1, 'l');   //find the next 'l'    printf("%s\n",p);        return 0;}//output lo#include #include #include int main(int argc, char const *argv[]){    char s[] = "Hello";    char *p = strchr(s, 'l');   //find string after the first 'l'    char *t = (char*)malloc(strlen(p)+1);   //replicate result to another variable    strcpy(t, p);    printf("%s\n",t);   //notice here is 't' rather 'p'    free(t);    //remenber to free it!        return 0;}//output llo#include #include #include int main(int argc, char const *argv[]){    char s[] = "Hello";    char *p = strchr(s, 'l');       char c = *p;    //c = 'l'    *p = '\0';  //when p point to 'l', replace 'l' with '\0'    char *t = (char*)malloc(strlen(s)+1);    strcpy(t, s);       printf("%s\n",t);       free(t);            return 0;}//output he//use c&t to reset s('l'), 
0 0
原创粉丝点击