一些c的字符串操作

    xiaoxiao2021-03-25  99

    1.char *strcat1(char *s,const char *ct);

    将串ct接到串s的后面,形成一个长串。以数组为参数,现用指针为参数。

    #include <stdio.h>

    #include<stdlib.h>

    char*strcat1(char *s, const char *ct) {

    char *st = s;

    while (*s)s++;//*s

    while (*s++ = *ct++) {};

    return st;

    } int main() {

    char a[120]="liming";

    char b[80]=" is a student";

    char *p;

    p=strcat1(a,b);

    printf("%s\n",p);

    system("pause");

    return 0;

    }

    2.int strlen1(const char * s);

    求字符串长度的函数,返回串长(不包括串结束符)。

    #include <stdio.h>

    #include<stdlib.h>

    int strlen1(const char *s) {

    int i = 0;

    while (*s++)i++;

    return i;

    }

    int main() {

    char a[] = "wujie";

    int b;

    b = strlen1(a);

    printf("%d\n", b);

    system("pause");

    return 0;

    }

    3.char * reverse (char *);

    反置字符串s,即可将“break”成为“kaerb”。

    #include <stdio.h>

    #include<stdlib.h>

    void reverse(char *s)  { char temp, *temp1 = s, *temp2 = s; while (*temp2)  temp2++; temp2--; while (temp2 - temp1>0) { temp = *temp1; *temp1++ = *temp2; *temp2-- = temp; } }

    int main() {

    char a[] = "wujie";

    char b[10];

    reverse(a);

    printf("%s\n", a);

    system("pause");

    return 0; }

    4.char * strchr( const char *cs,char c);

    查找字符c在串cs中第一次出现的位置,返回指向该字符的指针,若没有出现则返回NULL。

    #include <stdio.h>

    #include<stdlib.h>

    char *strchr(const char *cs, char c) {

    while (*cs != c&&*cs)cs++;

    if (*cs == 0)cs = NULL;

    return(char*)cs;

    }

    int main() {

    char a[] = "wujie";

    char b = 'j';

    char *c;

    c = strchr(a, b);

    if (c == NULL) { printf("未找到位置"); }

    else { printf("%s/n", c); }

    system("pause");

    return 0;

    }

    转载请注明原文地址: https://ju.6miu.com/read-36289.html

    最新回复(0)