C++:提取点后的字符串
C++: Extract string after dot
我正在尝试提取字符串值中的文件扩展名部分。
例如,假设字符串值为"file.cpp",我需要提取"cpp"或".cpp"部分。
我尝试使用 strtok(),但它没有返回我正在寻找的内容。
使用该任务的find_last_of
和substr
:
std::string filename = "file.cpp";
std::string extension = "";
// find the last occurrence of '.'
size_t pos = filename.find_last_of(".");
// make sure the poisition is valid
if (pos != string::npos)
extension = filename.substr(pos+1);
else
std::cout << "Coud not find . in the stringn";
这应该给你cpp
答案。
这将起作用,但您必须确保为其提供一个带有点的有效字符串。
#include <iostream> // std::cout
#include <string> // std::string
std::string GetExtension (const std::string& str)
{
unsigned found = str.find_last_of(".");
return str.substr( found + 1 );
}
int main ()
{
std::string str1( "filename.cpp" );
std::string str2( "file.name.something.cpp" );
std::cout << GetExtension( str1 ) << "n";
std::cout << GetExtension( str2 ) << "n";
return 0;
}
string::find
方法将返回字符串中字符的第一个匹配项,而您希望最后一个出现项。
您更有可能在string::find_last_of
方法之后:
参考: http://www.cplusplus.com/reference/string/string/find_last_of/
下面是一个简单的 C 实现:
void GetFileExt(char* ext, char* filename)
{
int size = strlen(filename);
char* p = filename + size;
for(int i=size; i >= 0; i--)
{
if( *(--p) == '.' )
{
strcpy(ext, p+1);
break;
}
}
}
int main()
{
char ext[10];
char filename[] = "nome_del_file.txt";
GetFileExt(ext, filename);
}
您可以以此为起点。
相关文章:
- 从字符串中提取整数并形成一个数组
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- asn1c 不会从 asn.1 模块中提取八位字节字符串的默认值
- 如何在字符串中找到字符,然后在C++中提取其余的字符串
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 清除输入缓冲区后未提取字符串流
- 如何创建一个函数来提取向量内部字符串中的字段?
- 从没有空格的字符串中提取整数
- 如何使用正则表达式从字符串中提取值
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 提取字符串中的随机单词
- 将子字符串提取到最后 n 个分隔符C++
- 如何在C 中不带有弦乐和strtok的情况下拆分字符串(提取单词)
- Arduino中的字符串提取问题
- C++ 在将字符串提取到标量时处理溢出/下溢
- 将两个 '' 字符之间的子字符串提取到单独的数组中
- 字符提取与字符串提取有何不同
- 如何从输入字符串提取数值?c++
- 作为XML字符串提取请求/响应