Dolly
Dolly

Reputation: 277

How to extract part of a string in c++

To Extract part of a string in a given line:

Given line is:

D:\AB554P_Itr23\ModelDir\AB554P_approximation_NodeData.dat Read 3/18/2010

I need to extract only the file name AB554P_approximation_NodeData.dat. I am using CodeGear RAD Studio C++ Builder. Thanks:)

Upvotes: 1

Views: 5928

Answers (6)

SChepurin
SChepurin

Reputation: 1854

  1. Here C++ Parse Split Delimited String you get the main function.
  2. To delete part after space, use:

string s = "D:\AB554P_Itr23\ModelDir\AB554P_approximation_NodeData.dat Read 3/18/2010";

size_t pos;
pos = s.find(" ");
s.erase(pos);

Now call split for '\' to split the remaining part.

Upvotes: 1

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145457

In order to handle Windows paths, use the Windows API path functions, such as PathFindFileName.

Cheers & hth.,

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 613592

The RTL function ExtractFileName() will extract the file name from a path.

Exactly how to split the 3 fields in your example depends very much on what the rules are for forming that line of text. How is it delimited? Is is delimited by spaces? If so, how do you escape spaces in the file path? Until you specify that information, that part of your question is unanswerable.

Upvotes: 3

Andrew White
Andrew White

Reputation: 53526

How about Boost::Filesystem...

string name = path( "D:\\AB554P_Itr23\\ModelDir\\AB554P_approximation_NodeData.dat").filename()

Upvotes: 4

Sadique
Sadique

Reputation: 22851

Did you look into string::substr

Upvotes: 4

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272812

You may want to investigate a regular expression library, such as Boost Regex.

Upvotes: 0

Related Questions