C++ 检测一个string字符串是否为全中文
时间: 2024-01-01 13:03:32 浏览: 33
可以使用正则表达式来检测一个string字符串是否为全中文。以下是一个示例代码:
```c++
#include <iostream>
#include <regex>
int main() {
std::string str = "这是全中文";
std::regex pattern("[\\u4e00-\\u9fa5]+"); // 匹配所有中文字符
if (std::regex_match(str, pattern)) {
std::cout << "字符串为全中文" << std::endl;
} else {
std::cout << "字符串不为全中文" << std::endl;
}
return 0;
}
```
其中,正则表达式 `[\\u4e00-\\u9fa5]+` 匹配所有中文字符。如果字符串中包含除中文字符以外的字符,则返回不为全中文。
相关问题
C++ 检测一个string字符串是否为全英文
可以通过遍历字符串的每一个字符,判断其 ASCII 码是否在英文字母的范围内来检测一个 string 字符串是否为全英文。具体实现可以参考以下代码:
```c++
#include <iostream>
#include <string>
using namespace std;
bool isEnglish(string str) {
for (int i = 0; i < str.length(); i++) {
if (!((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))) {
return false;
}
}
return true;
}
int main() {
string str = "HelloWorld";
if (isEnglish(str)) {
cout << "The string is all English letters." << endl;
} else {
cout << "The string is not all English letters." << endl;
}
return 0;
}
```
输出结果:
```
The string is all English letters.
```
C++怎么判断一个string字符串最后一个字符为:
可以使用string的length()方法获取字符串的长度,然后用字符串下标访问最后一个字符,即字符串长度减一的位置,如下所示:
string str = "hello world!";
char lastChar = str[str.length()-1]; // 获取最后一个字符
也可以使用string的back()方法获取最后一个字符,如下所示:
string str = "hello world!";
char lastChar = str.back(); // 获取最后一个字符