C语言练习_day5

C语言练习_day5

练习1

实现 mystrcpy(), mystrcmp(), mystrcat(), mystrlen() ;
图1

//mystrcpy(), mystrcmp(), mystrcat(), mystrlen();
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

char *mystrcpy(char *to, const char *from) {
	int i = 0;
	for (; to[i] != '\0'; ++i) {
		to[i] = '\0';
	}
	for (i = 0; from[i] != '\0';++i) {
		to[i] = from[i];
	}
	return to;
}

int mystrcmp(const char *str1, const char *str2) {
	int i = 0;
	for (; str1[i] != 0 || str2[i] != 0; ++i) {
		if (str1[i] > str2[i]) {
			return 1;
		}
		else if (str1[i] < str2[i]) {
			return -1;
		}
		else {
			continue;
		}
	}
	return 0;
}

char *mystrcat(char *str1, char *str2) {
	int i = 0, j = 0;
	//寻找到第一个字符串的末尾
	while (str1[i] != '\0') {
		++i;
	}
	for (; str2[j] != '\0'; ++j, ++i) {
		str1[i] = str2[j];
	}
	if (str1[i + 1] != '\0') {
		str1[i + 1] = '\0';
	}
	return str1;
}

unsigned mystrlen(char *str) {
	unsigned counter = 0;
	for (int i = 0; str[i] != '\0'; ++i) {
		++counter;
	}
	return counter;
}

int main() {
	char a[50] = "Hello ";
	char b[10] = "world!";
	char c[10] = "Hellopqr!";
	printf("%s\n", mystrcpy(c, b));
	printf("%d\n", mystrcmp(a, c));
	printf("%s\n", mystrcat(a, b));
	printf("%d\n", mystrlen(a));
	system("pause");
}

练习2

输入一行字符串(单词和若干空格), 输出该行单词个数。
Input:hello_________world how___are___you\n
Output: 5
图2

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

unsigned wordNumber(char *str) {
	unsigned counter = 0;
	for (int i = 0; str[i] != '\0'; ++i) {
		if ('a' <= str[i] && str[i] <= 'z'&&(str[i + 1] == ' '||str[i+1]=='\0')) {
			++counter;
		}
	}
	return counter;
}
int main() {
	char a[100] = { 0 };
	printf("Please enter a line of text:\n");
	gets(a);	//输入的字符串最后并不包含'\n'
	printf("There are %d words.\n", wordNumber(a));
	system("pause");
}

练习3

输入一行字符串(单词和若干空格),输出该行单词(每个单词一行)
Input:____hello_________world_ how___are___you___\n
Output: hello
    world
    how
    are
    you
图3

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void printWord(char *str) {
	unsigned counter = 0;
	for (int i = 0; str[i] != '\0'; ++i) {
		if ('a' <= str[i] && str[i] <= 'z' || ('A' <= str[i] && str[i] <= 'Z')) {
			printf("%c",str[i]);
		}
		else if ('a' <= str[i - 1] && str[i - 1] <= 'z'&&str[i] == ' ') {
			printf("\n");
		}
	}
	printf("\n");
}

int main() {
	char a[100] = { 0 };
	printf("Please enter a line of text:\n");
	gets(a);	//输入的字符串最后并不包含'\n'
	printWord(a);
	system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值