常见的字符串处理如substr
就不再赘述了。
stringstream
字符串到其他数据类型的转换:
#include <iostream>
#include <sstream>
int main() {
std::string str = "12345";
std::stringstream ss(str);
int num;
ss >> num;
std::cout << "The parsed integer is: " << num << std::endl;
float f;
ss >> f;
std::cout << "The parsed float is: " << f << std::endl;
double d;
ss >> d;
std::cout << "The parsed double is: " << d << std::endl;
return 0;
}
其他数据类型到字符串的转换:
#include <iostream>
#include <sstream>
int main() {
int num = 12345;
std::stringstream ss;
ss << num;
std::string str = ss.str();
std::cout << "The converted string is: " << str << std::endl;
return 0;
}
stringstream转string
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
ss << "Hello, ";
ss << "world!";
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}
注意箭头的方向和cin
, cout
有所区别。
strstr()
函数
在C++中,strstr
函数用于在一个字符串中搜索另一个字符串的出现位置。它的声明如下:
char* strstr(const char* str1, const char* str2);
类似于kmp,可以在O(n)时间内匹配字符串。
简单用法示例:
#include <iostream>
#include <cstring>
int main() {
const char* str1 = "Hello, world!";
const char* str2 = "world";
char* result = strstr(str1, str2);
if (result != nullptr) {
std::cout << "Substring found at position: " << (result - str1) << std::endl;
} else {
std::cout << "Substring not found." << std::endl;
}
return 0;
}
精简版:
#include <iostream>
#include <cstring>
using namespace std;
int main() {
string s1 = "hello, world!", s2 = "world";
auto p = strstr(s1.c_str(), s2.c_str());
cout << (p ? p - s1.c_str() : -1) << endl;
return 0;
}
sscanf和sprintf
可以读指定格式的字符串,比如日期。
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// 从输入字符串中读取指定格式的数据
string input = "John 25";
char name[100];
int age;
sscanf(input.c_str(), "%s %d", name, &age);
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
// 格式化输出字符串
char output[100];
sprintf(output, "Name: %s, Age: %d", name, age);
cout << "Formatted output: " << output << endl;
return 0;
}