#5515. 字符串输入以及函数笔记(包含char数组和字符串)

字符串输入以及函数笔记(包含char数组和字符串)

🎯 字符与字符串操作大全

📝 一、字符类型的操作

🔤 字符基础操作

操作 语句及解释 示例
字符的定义 char ch char grade = 'A';
字符的读入 cin >> ch //跳过空格或回车 cin >> inputChar;
ch = getchar() //读取所有字符 ch = getchar();
scanf("%c", &ch) //读取所有字符 scanf("%c", &ch);

⚠️ 重要注意事项

  • 回车(换行)符'\n' ↩️
  • 文件结束符EOF 🏁

📖 读取字符直到文件结束的经典模式

ch = getchar();    // 不断读入字符直到文件结束
while(ch != EOF)   // 🎯 文件未结束就继续读取
{
    a[++n] = ch;   // 📥 存储字符
    ch = getchar(); // 🔄 读取下一个字符
}

🖨️ 字符的输出

操作 代码
输出字符 cout << ch;
格式化输出 printf("%c", ch)
带换行输出 printf("%c\n", ch)

🔍 字符判断函数

判断类型 代码 示例
判断数字 if(ch >= '0' && ch <= '9') if(isdigit(ch)) 🔢
判断小写字母 if(ch >= 'a' && ch <= 'z') if(islower(ch)) 📝
判断大写字母 if(ch >= 'A' && ch <= 'Z') if(isupper(ch)) 🅰️

🗂️ 二、字符数组的操作

📦 字符数组定义

char a[100];  // 🎒 定义能存储100个字符的数组

📥 字符数组的读入和输出

// 方式1:逐个字符读入
for(int i = 1; i <= n; i++) {
    cin >> a[i];           // 🚫 跳过空格
    // 或
    a[i] = getchar();      // ✅ 读取所有字符
    // 或  
    scanf("%c", &a[i]);    // ✅ 读取所有字符
}

// 方式2:整体字符串读入
scanf("%s", a);           // 📚 读取整个字符串
// 或
scanf("%s", &a);          // 📚 同样效果

// 输出整个字符串
cout << a;                // 🖨️ 直接输出
printf("%s", a);          // 🖨️ 格式化输出

🎯 特殊读入技巧

scanf("%s", a + 2);  // 🎪 从数组第2位开始存放字符串
// 注意:此时不能用printf直接输出,需要循环输出
for(int i = 2; a[i] != '\0'; i++) {
    cout << a[i];
}

🛠️ 三、字符数组的相关函数

📋 字符串函数大全

函数 功能描述 示例 注意事项
strcpy(dest, src) 📤 字符串拷贝 strcpy(str1, str2) 目标数组要足够大
strcat(dest, src) 🔗 字符串连接 strcat(str1, str2)
strcmp(str1, str2) ⚖️ 字符串比较 strcmp(a, b) 返回0表示相等
strlen(str) 📏 字符串长度 strlen("hello") 返回5
strlwr(str) 🔽 转小写 strlwr(str) 原地修改
strupr(str) 🔼 转大写 strupr(str)

🎯 详细函数说明

(a) strcpy - 字符串拷贝 📤

char str1[10];
char str2[] = "china";
strcpy(str1, str2);  // 🎯 把str2拷贝到str1

// 其他用法:
strcpy(str1, "china");        // ✅ 直接拷贝字符串常量
strncpy(str1, str2, 2);       // ✅ 只拷贝前2个字符

⚠️ 重要提醒:

  • ❌ 错误写法:str1 = "china";
  • ❌ 错误写法:str2 = str1;
  • ✅ 正确写法:必须使用strcpy函数

(b) strcat - 字符串连接 🔗

char str1[80] = "people's republic of ";
char str2[] = "china";
strcat(str1, str2);    // 🎯 连接两个字符串
cout << str1;          // 输出:people's republic of china

(c) strcmp - 字符串比较 ⚖️

// 🎯 判断两个字符串是否相等
if(strcmp(a, b) == 0) {
    cout << "两个字符串相等! 🎉";
} else {
    cout << "两个字符串不相等! 😞";
}

// ❌ 错误写法:if(str1 == str2)
// ✅ 正确写法:if(!strcmp(str1, str2))

(d) strlen - 字符串长度 📏

char str[80] = "people";
cout << strlen(str) << endl;  // 📊 输出:6

(e) 大小写转换函数

strlwr(str);  // 🔽 大写转小写
strupr(str);  // 🔼 小写转大写

🎓 实际应用示例

#include<iostream>
#include<string.h>
using namespace std;

int main() {
    char s[200];
    int count, i, j;
    cout << "Input a string: \n";
    cin.getline(s, 200);  // 📥 读取一行字符串
    
    // 🎯 统计单词数量
    for(count = 0, j = strlen(s), i = 0; i < j; ) {
        while(s[i] == ' ' && i < j) i++;     // 🚀 跳过空格
        if(i < j) count++;                   // 📊 找到单词,计数+1
        while(s[i] != ' ' && i < j) i++;     // 🚀 跳过当前单词
    }
    
    cout << s << '\n';
    cout << "The count is: " << count << '\n';
}

🎪 四、字符串类型的相关操作

🆚 string vs 字符数组

特性 字符数组 string类
定义 char arr[100] string str
长度 固定 动态 📈
安全性 可能越界 🚫 自动管理 ✅
功能 需要函数 内置方法 🎯

📚 string类基本操作

string st;                    // 📦 定义字符串

// 📥 输入输出
cin >> st;                    // 🚀 读入(跳过空格回车)
getline(cin, st);             // 📖 读取整行
cout << st;                   // 🖨️ 输出

// 📏 长度测量
int len = st.size();          // ✅ 推荐
int len2 = st.length();       // ✅ 同样效果

🛠️ string类常用成员函数

函数 功能 示例
substr(pos, len) ✂️ 获取子串 st.substr(2, 5)
empty() 🔍 判断空串 if(st.empty())
insert(pos, str2) 📎 插入字符串 st.insert(3, "abc")
erase(pos, len) 🗑️ 删除子串 st.erase(2, 3)
find(str1) 🔎 查找子串 st.find("hello")
rfind(str1) 🔍 反向查找 st.rfind("world")

🎯 查找函数使用技巧

// 🎯 判断是否找到子串
if(st.find("hello") != string::npos) {  // ✅ 找到子串
    cout << "找到hello! 🎉" << endl;
} else {
    cout << "没找到hello! 😞" << endl;
}

🔄 替换函数

// 方法1:指定位置和长度
st.replace(2, 5, "new_str");  // ✨ 从位置2开始替换5个字符

// 方法2:使用迭代器
replace(st.begin(), st.begin() + 5, "new_str");  // 🎯 替换前5个字符

🔄 类型转换

string str = "hello";
const char* c_str = str.c_str();  // 🔄 string转C风格字符串

🎨 五、字符串的排序

1. 单个字符串内部排序 🎯

🔼 ASCII码从小到大排序

#include<bits/stdc++.h>
using namespace std;

int main() {
    string st;
    cin >> st;
    sort(st.begin(), st.end());  // 🎯 默认升序排序
    cout << st;
    return 0;
}

🔽 ASCII码从大到小排序

方法一:使用cmp函数

#include<bits/stdc++.h>
using namespace std;

bool cmp(char a, char b) {
    return a > b;  // 🎯 降序比较
}

int main() {
    string st;
    cin >> st;
    sort(st.begin(), st.end(), cmp);  // 🎯 使用自定义比较函数
    cout << st;
    return 0;
}

方法二:使用反向迭代器

#include<bits/stdc++.h>
using namespace std;

int main() {
    string st;
    cin >> st;
    sort(st.rbegin(), st.rend());  // 🎪 反向迭代器实现降序
    cout << st;
    return 0;
}

2. 多个字符串排序 📚

🔼 按ASCII码从小到大排序

#include<bits/stdc++.h>
using namespace std;

string a[4];

int main() {
    for(int i = 0; i < 4; i++)
        getline(cin, a[i]);      // 📥 读取4个字符串
    
    sort(a, a + 4);              // 🎯 默认升序排序
    
    for(int i = 0; i < 4; i++)
        cout << a[i] << endl;    // 🖨️ 输出排序结果
    return 0;
}

🔽 按ASCII码从大到小排序

#include<bits/stdc++.h>
using namespace std;

string a[4];

int main() {
    for(int i = 0; i < 4; i++)
        getline(cin, a[i]);
    
    sort(a, a + 4, greater<string>());  // 🎯 使用greater实现降序
    
    for(int i = 0; i < 4; i++)
        cout << a[i] << endl;
    return 0;
}

3. 部分排序技巧 🎪

对字符串前5个字符排序

#include<bits/stdc++.h>
using namespace std;

bool cmp(char a, char b) {
    return a > b;  // 🎯 降序比较
}

int main() {
    string st;
    cin >> st;
    sort(st.begin(), st.begin() + 5, cmp);  // 🎪 只排序前5个字符
    cout << st;
    return 0;
}

💡 学习建议

  1. 🧠 理解差异:分清字符数组和string类的使用场景
  2. 💻 多写多练:每个函数都要亲手敲一遍代码
  3. 🎯 记住重点:字符串比较必须用strcmp,不能用==
  4. 🚀 灵活运用:根据需求选择最合适的字符串处理方法

掌握这些字符串操作,你就能轻松应对各种文本处理任务!🎉👨‍💻