C++ 判断字符串是否符合格式的几种方式
时间: 2023-12-03 12:02:20 浏览: 87
判断字符串是否符合特定格式可以使用正则表达式、字符串匹配、字符遍历等方法。以下是几种常见的方式:
1. 正则表达式:使用正则表达式匹配字符串是否符合特定模式。C++ 中可以使用 std::regex 类来进行正则表达式匹配。
```cpp
#include <regex>
#include <iostream>
int main() {
std::string str = "1234-5678-9012-3456";
std::regex pattern("\\d{4}-\\d{4}-\\d{4}-\\d{4}");
if (std::regex_match(str, pattern)) {
std::cout << "Match!" << std::endl;
} else {
std::cout << "Not match!" << std::endl;
}
}
```
2. 字符串匹配:使用字符串库函数如 strstr()、strchr() 等查找字符串中是否包含特定的子串。
```cpp
#include <iostream>
#include <cstring>
int main() {
std::string str = "hello world";
char substr[] = "world";
if (std::strstr(str.c_str(), substr) != nullptr) {
std::cout << "Match!" << std::endl;
} else {
std::cout << "Not match!" << std::endl;
}
}
```
3. 字符遍历:遍历字符串中的每一个字符,检查是否符合特定要求。
```cpp
#include <iostream>
#include <cstring>
int main() {
std::string str = "1234-5678-9012-3456";
bool is_valid = true;
for (int i = 0; i < str.size(); i++) {
if (i % 5 != 4 && !std::isdigit(str[i])) {
is_valid = false;
break;
}
if (i % 5 == 4 && str[i] != '-') {
is_valid = false;
break;
}
}
if (is_valid) {
std::cout << "Valid format!" << std::endl;
} else {
std::cout << "Invalid format!" << std::endl;
}
}
```
以上三种方法都可以用来判断字符串是否符合特定格式,具体选择哪一种方法取决于具体的需求和实现复杂度。