00.13_字符串
字符串
问题描述
字符串是一种特殊的序列,用于存储字符数据。
在C++中为string,Java中为String,Python中为str。
它们都提供了丰富的字符串处理方法。
基本概念
特点
- 字符序列
- 支持随机访问
- 提供字符串操作
- 不可变性(Java和Python)
- 支持迭代遍历
代码实现
- C++ String
#include <iostream>
#include <string>
using namespace std;
int main() {
// 创建字符串
string str1; // 空字符串
string str2 = "Hello"; // 直接初始化
string str3(5, 'a'); // 包含5个'a'
string str4 = str2 + ", World"; // 字符串连接
// 访问和修改
cout << str2[0] << endl; // 使用下标访问:H
str2[0] = 'h'; // 修改字符
cout << str2 << endl; // 输出:hello
// 字符串操作
cout << str2.length() << endl; // 长度:5
cout << str2.size() << endl; // 同length():5
str2.append("!"); // 追加
str2.push_back('!'); // 添加单个字符
str2.insert(5, " there"); // 插入子串
str2.erase(5, 6); // 删除子串
// 查找
size_t pos = str4.find("World");
if (pos != string::npos) {
cout << "Found at: " << pos << endl;
}
// 子串
string sub = str4.substr(0, 5); // 提取前5个字符
string sub2 = str4.substr(7); // 从位置7到末尾的子串
cout << sub << endl; // 输出:Hello
cout << sub2 << endl; // 输出:World
// 比较
if (str1 < str2) {
cout << "str1 is less than str2" << endl;
}
return 0;
}
- Java String
public class Main {
public static void main(String[] args) {
// 创建字符串
String str1 = ""; // 空字符串
String str2 = "Hello"; // 直接初始化
String str3 = "a".repeat(5); // 包含5个'a'
String str4 = str2 + ", World"; // 字符串连接
// 访问字符
System.out.println(str2.charAt(0)); // 获取字符:H
// 字符串操作
System.out.println(str2.length()); // 长度:5
str2 = str2.toLowerCase(); // 转小写
System.out.println(str2); // 输出:hello
// StringBuilder用于频繁修改
StringBuilder sb = new StringBuilder(str2);
sb.append("!"); // 追加
sb.insert(5, " there"); // 插入子串
sb.delete(5, 11); // 删除子串
str2 = sb.toString();
// 查找
int pos = str4.indexOf("World");
if (pos != -1) {
System.out.println("Found at: " + pos);
}
// 子串
String sub = str4.substring(0, 5); // 提取子串
System.out.println(sub); // 输出:Hello
// 比较
if (str1.compareTo(str2) < 0) {
System.out.println("str1 is less than str2");
}
// 分割和连接
String text = "apple,banana,orange";
String[] parts = text.split(",");
String joined = String.join("-", parts);
System.out.println(joined); // 输出:apple-banana-orange
}
}
- Python String
# 创建字符串
str1 = "" # 空字符串
str2 = "Hello" # 直接初始化
str3 = "a" * 5 # 包含5个'a'
str4 = str2 + ", World" # 字符串连接
# 访问字符
print(str2[0]) # 获取字符:H
# str2[0] = 'h' # 错误:字符串不可修改
# 字符串操作
print(len(str2)) # 长度:5
str2 = str2.lower() # 转小写
print(str2) # 输出:hello
# 查找
pos = str4.find("World")
if pos != -1:
print(f"Found at: {pos}")
# 子串和切片
sub = str4[0:5] # 提取子串
print(sub) # 输出:Hello
print(str4[::-1]) # 反转字符串
# 分割和连接
text = "apple,banana,orange"
parts = text.split(",")
joined = "-".join(parts)
print(joined) # 输出:apple-banana-orange
# 字符串方法
print("hello".upper()) # 转大写
print(" text ".strip()) # 去除两端空白
print("hello".replace('l', 'L')) # 替换字符
print("hello".count('l')) # 计数
print("123".isdigit()) # 检查是否为数字
print("abc".isalpha()) # 检查是否为字母
# 格式化
name = "Alice"
age = 20
print(f"{name} is {age} years old") # f-string
print("{} is {} years old".format(name, age)) # format方法
print("%s is %d years old" % (name, age)) # %操作符
应用场景
- 文本处理
- 数据解析
- 用户输入
- 文件操作
- 网络通信
注意事项
- 字符串不可变性(Java和Python)
- 字符编码
- 内存管理
- 性能优化
- 字符串池
- 子串操作差异
- C++: substr(pos, len) 从pos开始,长度为len
- Java: substring(begin, end) 从begin到end-1
- Python: s[begin:end] 从begin到end-1
常见示例
- 回文字符串判断
bool isPalindrome(string s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s[left] != s[right]) return false;
left++;
right--;
}
return true;
}
public static boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left) != s.charAt(right)) return false;
left++;
right--;
}
return true;
}
def is_palindrome(s: str) -> bool:
return s == s[::-1] # 使用切片反转
- 单词统计
map<string, int> countWords(string text) {
map<string, int> counts;
stringstream ss(text);
string word;
while (ss >> word) {
counts[word]++;
}
return counts;
}
public static Map<String, Integer> countWords(String text) {
Map<String, Integer> counts = new HashMap<>();
for (String word : text.split("\\s+")) {
counts.put(word, counts.getOrDefault(word, 0) + 1);
}
return counts;
}
def count_words(text: str) -> dict:
return Counter(text.split()) # 使用Counter类
牛客代码笔记-牛栋 文章被收录于专栏
汗牛充栋,学海无涯。<br/> 内含算法知识点讲解,以及牛客题库精选例题。<br/> 学习算法,从牛栋开始。