class-notes/2208/C语言/字符串处理.md
2025-03-14 11:18:41 +08:00

101 lines
1.8 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 <string.h>
int main(){
char str[100];
char temp;
int i, j;
gets(str);
for(i=0;i<strlen(str)-1;i++){
for(j=0;j<strlen(str)-1-i;j++){
if(*(str+j) > *(str+j+1)){
temp = *(str+j);
*(str+j) = *(str+j+1);
*(str+j+1) = temp;
}
}
}
puts(str);
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