2.编写程序:用指针变量编写下列字符串处理函数: 1)字符串拼接函数 2)字符串比较函数 3)取字符串长度函数
时间: 2024-05-02 18:18:30 浏览: 74
1)字符串拼接函数:
```c
#include <stdio.h>
void string_concat(char *s1, char *s2) {
while (*s1 != '\0') {
s1++;
}
while (*s2 != '\0') {
*s1 = *s2;
s1++;
s2++;
}
*s1 = '\0';
}
int main() {
char s1[20] = "hello";
char s2[20] = "world";
string_concat(s1, s2);
printf("%s\n", s1);
return 0;
}
```
2)字符串比较函数:
```c
#include <stdio.h>
int string_compare(char *s1, char *s2) {
while (*s1 == *s2) {
if (*s1 == '\0') {
return 0;
}
s1++;
s2++;
}
return (*s1 - *s2);
}
int main() {
char s1[20] = "hello";
char s2[20] = "world";
int result = string_compare(s1, s2);
if (result < 0) {
printf("%s is less than %s\n", s1, s2);
} else if (result > 0) {
printf("%s is greater than %s\n", s1, s2);
} else {
printf("%s is equal to %s\n", s1, s2);
}
return 0;
}
```
3)取字符串长度函数:
```c
#include <stdio.h>
int string_length(char *s) {
int length = 0;
while (*s != '\0') {
length++;
s++;
}
return length;
}
int main() {
char s[20] = "hello";
int length = string_length(s);
printf("The length of %s is %d\n", s, length);
return 0;
}
```
阅读全文