C语言练习

来源:互联网 发布:真实女友3优化补丁 编辑:程序博客网 时间:2024/05/06 17:08

字符串逆序:设计一个函数void f(char * p),对p指向的字符串进行逆序。要求函数f()中不能定义任何数组,
不能调用任何字符串处理函数。在main()中,输入字符串,调用f(),
最后输出逆序后的字符串。

#include <stdio.h>void f( char* p );int main() {    char ch[20];    int i = 0;    while( ( ch[i] = getchar() ) != '\n' ) {        i++;    }    ch[i] = '\0';    f( ch );    return 0;}void f( char* p ) {    int i = 0,l,temp;    int length = 0;    while( *(p+i) != '\0' ) {        length++;        i++;    }    i = 0;    l = length-1;//l是字符串真正个数    for( i = 0; i <= l/2; l--,i++ ) {        temp = *(p+i);        *(p+i) = *(p+l);        *(p+l) = temp;    }    for( i = 0; i < length; i++ ) {        printf("%c", *(p+i));    }}

删除字符:输入一个字符串s,再输入一个字符c,将字符串s中出现的所有字符c
删除。要求定义并调用函数delchar(s,c),它的功能是将字符串s中出现的所有
字符c删除。

#include <stdio.h>#include <string.h>void delchar(char * p, char c);int main() {    char str[80];    char ch;    int i = 0;    printf("请输入1个字符串和1个字符:");    scanf("%s %c", str,&ch);    delchar(str,ch);    printf("%s", str);    return 0;}void delchar(char * str, char c) {    char * p = str;    while( *str != '\0' ) {//字符串不为空循环判断每个数与c是否相等        if( *p == c ) {//如果相等,循环把后面的所有字符往前移一位            while( *p != '\0' ) {                *p = *(p+1);                p = p+1;            }        }        p = str += 1;    }}

使用函数实现字符串复制:输入一个字符串t和一个正数m,将字符串t中从第m个字符开始的全部字符复制到字符串s中,再输出字符串s。要求用字符串指针定义并调用
函数strmcpy(s,t,m),它的功能是将字符串t中从第m个字符开始的全部字符复制到字符串s中。

#include <stdio.h>#include <string.h>void strmcpy(char * s, char * t, int m);int main() {    char t[80];    char s[80];    int m;    int i = 0;    printf("请输入1个字符串和m:");    gets(t);    scanf("%d", &m);    strmcpy(s,t,m);    printf("%s", s);    return 0;}void strmcpy(char * s, char * t, int m) {    while( *t != '\0' ) {//字符t不为空,循环复制从第m-1个字符到s中        *s = *(t + (m-1));        s++;        t++;    }}

判断回文字符串:判断输入的一串字符是否为“回文”。所谓“回文”,是指顺读和倒读都一样的字符串。如“XYZYX”和“xyzyx”都是回文。

#include <stdio.h>#include <string.h>int isPlalindrome(char * s);int main() {    char t[80];    char s[80];    int m;    int i = 0;    printf("请输入1个字符串:");    scanf("%s", s);    if( isPlalindrome(s) ) {        printf("%s是回文", s);    } else {        printf("%s不是回文", s);    }    return 0;}int isPlalindrome(char * s) {    int i = 1;    int k = 0;    char * p = s;    char * q = s;    while( *(s++) != '\0' ) {        k++;//k是字符串的长度    }    while( *p != '\0' ) {        if( *p != *(q+k-1) ) {            i = 0;            break;        }        p++;        k--;    }    return i;}
0 0
原创粉丝点击