C++:提取点后的字符串

C++: Extract string after dot

本文关键字:字符串 提取 C++      更新时间:2023-10-16

我正在尝试提取字符串值中的文件扩展名部分。

例如,假设字符串值为"file.cpp",我需要提取"cpp"或".cpp"部分。

我尝试使用 strtok(),但它没有返回我正在寻找的内容。

使用该任务的find_last_ofsubstr

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);
}

您可以以此为起点。