1. 程式人生 > >一些c的字串操作

一些c的字串操作

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;

}