练习1
实现 mystrcpy(), mystrcmp(), mystrcat(), mystrlen() ;
//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
#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
#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");
}