天天看點

C語言練習_day5練習1練習2練習3

C語言練習_day5

  • 練習1
  • 練習2
  • 練習3

練習1

實作 mystrcpy(), mystrcmp(), mystrcat(), mystrlen() ;

C語言練習_day5練習1練習2練習3
//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

C語言練習_day5練習1練習2練習3
#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

C語言練習_day5練習1練習2練習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");
}
           

繼續閱讀