c++string标点符号
时间: 2025-03-06 08:34:17 浏览: 11
C++ 中处理 string
和标点符号的方法
去除英文标点符号
为了去除输入字符串中的英文标点符号,可以利用 <cctype>
库里的 ispunct()
函数来检测字符是否属于标点类别。通过遍历整个字符串并仅保留非标点字符的方式实现这一功能[^2]。
#include <iostream>
#include <string>
#include <cctype>
int main() {
std::string input;
getline(std::cin, input);
std::string result;
for (char& ch : input) {
if (!std::ispunct(ch)) {
result += ch;
}
}
std::cout << result;
return 0;
}
处理 UTF-8 字符串中的中英文标点符号
对于包含中文和其他多字节字符集(如UTF-8)的字符串来说,简单的 ASCII 标点过滤可能不够充分。此时应该考虑更复杂的方案,比如先将字符串转换成宽字符形式 (wstring
) 后再做进一步处理[^3]。
#include <iostream>
#include <string>
#include <cwchar> // For mbstowcs()
std::wstring StringToWString(const std::string& str) {
size_t len = str.size();
wchar_t* buffer = new wchar_t[len];
mbstowcs(buffer, str.c_str(), len);
std::wstring wstr(buffer);
delete[] buffer;
return wstr;
}
bool IsPunctuation(wchar_t wc) {
static const wchar_t punctuation_chars[] =
L".,!?;:'\"()-[]{}<>@#$%^&*~|/\\";
for (wchar_t c : punctuation_chars)
if (wc == c) return true;
return false;
}
void RemoveAllPunctuation(std::wstring& text) {
auto it = std::remove_if(text.begin(), text.end(),
[](wchar_t ch){return IsPunctuation(ch);});
text.erase(it, text.end());
}
int main() {
std::string utf8_input;
getline(std::cin, utf8_input);
std::wstring wide_text = StringToWString(utf8_input);
RemoveAllPunctuation(wide_text);
std::wcout.imbue(std::locale(""));
std::wcout << wide_text;
return 0;
}
上述代码展示了如何从给定的 UTF-8 编码字符串中移除所有的英文字母以及指定列表内的常见标点符号。注意,在实际应用中应当根据具体需求调整所要排除的具体字符集合。
判断文件内容是否存在特定类型的标点符号
当涉及到读取外部资源时,可以通过逐行解析每一行的内容来进行分析。如果目标是查找是否有任何一行包含了至少一个中文标点,则可以在每次遇到这样的情况时立即停止搜索并给出肯定的回答;反之则继续直到完成所有数据的扫描为止[^4]。
#include <fstream>
#include <codecvt> // Deprecated but still widely used for simplicity here.
#include <locale>
bool ContainsChinesePunctuation(const std::u16string& line) {
// Define a list of Chinese punctuations you want to check against...
static constexpr char16_t chinese_puncts[] = u",。!?、;:“”‘’《》【】…—";
for (char16_t ch : line) {
bool found = std::any_of(
std::begin(chinese_puncts),
std::end(chinese_puncts),
[&ch](const char16_t& punc){
return punc == ch;
});
if (found) return true;
}
return false;
}
bool FileHasChinesePunctuation(const std::string& filename) {
std::ifstream file(filename);
if (!file.is_open()) throw std::runtime_error("Failed opening the file.");
typedef std::codecvt_utf8<char16_t> convert_typeX;
std::wstring_convert<convert_typeX, char16_t> converter;
while(file.good()){
std::string sline;
std::getline(file,sline);
try{
std::u16string uline = converter.from_bytes(sline);
if(ContainsChinesePunctuation(uline)){
return true;
}
}catch(...){
continue;
}
}
return false;
}
这段程序定义了一个辅助函数用于检查某一行内是否含有预设好的几种典型中文标点之一,并提供另一个接口用来评估某个文本文件里任意位置上是否存在此类标记的存在。
阅读全文
相关推荐

















