跳到正文

算法·理论

字符串 -- C++ string

SunnyFishQwQ约 4 分钟
原文
文章信息与版本

文章信息

发布
2024年11月22日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 4 分钟

版本

  1. v1当前
C++
#include <iostream>
#include <cstring>
#include <cassert>
#define fori(na, st, ed) for (int na = st; na <= ed; na++)
#define forn(na, ed) fori(na, 1, ed)
#define fora(na, st, ed) for (int na = st; na >= ed; na--)
#define fors(na, st) fora(na, st, 1)
#define ll long long
using namespace std;
string s1, s2;
void couts(string &s) {
	puts(s.data());
}
void cins(string &s) {
	char k[(int)1e5];
	scanf("%s", k);
	s = k;
}
void getlines(string &s) {
	char k[(int)1e5];
	fgets(k, sizeof k, stdin);
	s = k; 
}
int main() {
	// 字符串拼接 
	s1 = "Hello";
	s2 = "world!";
	string s3 = s1 + s2;
	couts(s3);
	s3.append("123");
	couts(s3);
	
	// 字符串输入输出
	cin >> s3; // 空格和回车结束 
	cout << s3;
	
	cins(s3);
	couts(s3);
	
	// 读入一整行 
	getline(cin, s3);
	cout << s3 << endl; 
	
	getlines(s3);
	couts(s3);
	
	// 获取字符串长度
	int l1 = s1.length();
	cout << l1 << endl;
	int l2 = s1.size();
	cout << l2 << endl;
	assert(l1 == l2);
	
	// 字符串当字符数组使用
	cout << s1[0] << endl;
	cout << s1[2] << endl;
	
	// 字符串和字符数组的互换
	// string --> char[] 
	char a[(int)1e5];
	// 1.
	strcpy(a, s1.data());
	strcpy(a, s1.c_str());
	cout << a << endl;
	// 2.
	int lens = s1.copy(a, s1.length());
	a[lens] = '\0';
	cout << a << endl;
	// 3.
	strcpy(a, &s2[0]);
	cout << a << endl;
	
	// 字符串比较
	s1 = "abc";
	s2 = "abb";
	if (s1 > s2)
		cout << "s1 > s2" << endl;
	else
		cout << "s1 <= s2" << endl;
	
	s1 = "Abc";
	if (s1 > s2)
		cout << "s1 > s2" << endl;
	else
		cout << "s1 <= s2" << endl;
	
	s1 = "hello world";
	s2 = s1.substr(2, 5);
	cout << s2 << endl;
	couts(s2);
	s2 = s1.substr(3);
	cout << s2 << endl;
	couts(s2);
	
	// 查找子串
	int n = s1.find("world");
	cout << n << endl;
	cout << s1.find("o") << endl;
	cout << s1.find('o') << endl;
	cout << s1.rfind("o") << endl;
	cout << s1.rfind('o') << endl;
	cout << s1.find("ooooooo") << endl;
	
	// 替换字符串
	s1 = "hello World";
	s1.replace(0, 5, "school");
	cout << s1 << endl;
	couts(s1);
	
	// 删除子串
	s1 = "hello World";
	s1.erase(3, 3);
	cout << s1 << endl;
	couts(s1);
	
	// 插入子串
	s1 = "hello World";
	s1.insert(5, "aaaa");
	cout << s1 << endl;
	couts(s1);
	return 0;
}
原文