1

私は主にC++ライブラリから標準関数を探しています。これは、文字列内で文字を検索し、見つかった文字から始まる文字列の残りの部分を出力するのに役立ちます。次のシナリオがあります。

#include <string>

using std::string;

int main()
{
     string myFilePath = "SampleFolder/SampleFile";

     // 1. Search inside the string for the '/' character.
     // 2. Then print everything after that character till the end of the string.
     // The Objective is: Print the file name. (i.e. SampleFile).

     return 0;
}

よろしくお願いします。コードの完成を手伝っていただければ幸いです。

4

5 に答える 5

4

最後から始まる文字列から部分文字列を抽出することもできますが、/最も効率的にするには(つまり、印刷するデータの不要なコピーを作成しないようにするため)、次のように使用できstring::rfindますostream::write

string myFilePath = "SampleFolder/SampleFile";

size_t slashpos = myFilePath.rfind('/');

if (slashpos != string::npos) // make sure we found a '/'
    cout.write(myFilePath.data() + slashpos + 1, myFilePath.length() - slashpos);
else
    cout << myFilePath;

ファイル名を抽出して、すぐに印刷するのではなく後で使用する必要がある場合は、bert-janまたはxavierの回答が適しています。

于 2011-11-26T09:51:11.727 に答える
3

試す

size_t pos = myFilePath.rfind('/');
string fileName = myFilePath.substr(pos);
cout << fileName;
于 2011-11-26T09:52:58.260 に答える
0
 std::cout << std::string(myFilePath, myFilePath.rfind("/") + 1);
于 2011-11-26T09:52:29.087 に答える
0

_splitpath()を使用する場合があります。MSDNのhttp://msdn.microsoft.com/en-us/library/e737s6tf.aspxを参照してください。

このSTDRTL関数を使用して、パスをコンポーネントに分割できます。

于 2011-11-26T10:16:01.730 に答える
0

あなたの質問の目的を説明するこの行に基づいて:

// The Objective is: Print the file name. (i.e. SampleFile).

std :: filesystemを使用して、これを非常にうまく行うことができます。

#include <filesystem>
namespace fs = std::experimental::filesystem;

fs::path myFilePath("SampleFolder/SampleFile");
fs::path filename = myFilePath.filename();

拡張子のないファイル名のみが必要な場合:

#include <filesystem>
namespace fs = std::experimental::filesystem;

myFilePath("SampleFolder/SampleFile");
fs::path filename = myFilePath.stem();
于 2019-08-22T23:26:02.063 に答える