class-notes/2208/C语言/字符串处理.md
2025-03-17 18:51:31 +08:00

112 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

### 1. 计算空格、大小写字母
从键盘上输入一个字符串, 计算字符串里有多少个空格、小写字母、大写字母、数字。
```c
#include <stdio.h>
int main(){
char str[100], space, low_letter, upp_letter, number;
space = low_letter = upp_letter = number = 0;
char *p;
gets(str);
p = str;
while(*p != '\0'){
if(*p == ' '){
space++;
}else if(*p >= 'a' && *p <= 'z'){
low_letter++;
}else if(*p >= 'A' && *p <= 'Z'){
upp_letter++;
}else if(*p >= '0' && *p <= '9'){
number++;
}
p++;
}
printf("空格:%d 小写字母:%d 大写字母:%d 数字%d\n",
space, low_letter, upp_letter, number);
return 0;
}
```
### 2. 字符串排序
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 比较函数,用于 qsort
int compare_strings(const void *a, const void *b) {
return strcmp(*(const char **)a, *(const char **)b);
}
int main() {
// 测试用例:字符串数组
const char *strings[] = {
"banana",
"apple",
"cherry",
"date",
"blueberry"
};
// 计算数组的长度
int length = sizeof(strings) / sizeof(strings[0]);
// 使用 qsort 对字符串数组进行排序
qsort(strings, length, sizeof(const char *), compare_strings);
// 输出排序后的字符串数组
printf("Sorted strings:\n");
for (int i = 0; i < length; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
```
### 3. 字符串插入
字符串插入: “1234567890”
在第2个位置后面插入”ABC”
最终结果: “12ABC34567890”
### 4. 字符串查找
字符串查找: “123456123abc123hbc”
查找字符串”123”的数量。数量是3
### 5. 字符串删除
字符串删除: “1234567890”
删除”456” 最终结果: “1237890”
### 6. 字符串替换
### 7. 字符串转整数
从键盘上输入一个字符串”12345”, 得到整数: 12345;
### 8. 整数转字符串
整数转字符串。输入一个整数1234得到字符串: “1234”
### 9. 浮点数转字符串
浮点数转字符串。输入一个浮点数123.456 得到字符串"123.456"
### 10.字符串转浮点数
字符串转浮点数。输入一个字符串: “123.456” 得到浮点数类型: 123.456