Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

C++ String Manipulation Question

Status
Not open for further replies.

mjs84

Aerospace
Aug 20, 2003
27
0
0
US
I am a new C++ programmer that has been thrust into the belly of the C++ beast. I am having problems with trying to extract a substring from a string. The string and substrings will be of varying length, what I do know is I want to start grabbing the text after the last '\' until and keep grabbing until i hit the last '.'. Yes, I am trying to pull a piece of a file string.

ie...

str = "\\ddata\conf\src\bin\d_5032.dat"

I am trying to pull the "d_5032" from the string above and I want to assign it to a variable. I am using MS Visual C++ 6.0. Any help would be greatly appreciated.
 
Replies continue below

Recommended for you

I suppose that you take the string from a file content.

Hope this help you...

--
char *aux1,aux2[7],buffer[50],var[200];
// read a file line content up to the end
// of the line in the present string

fgets(buffer,200,file2);
sscanf(buffer,"%s", &var);
aux1=&var[0];
count=0;


// it gets the length of the captured line/string
// and put the
// aux1 vector at the end of the line/string_vector
aux1=&buffer[0];
aux1+=strlen(buffer);
for(i=0;if(!strcmp(buffer,"\"));i++)
{ // you move back the position to the
// begining of the string and stop it
// when you find the character "\"
aux1--;
}

for(i=0;i<fileN_character;i++)
{ // now you copy letter by letter from the file name
aux2=*aux1; aux1++;
}

// yet at aux2 you have the file name!...{:ß).

--
Tom
 
Were you wanting to use std::string member functions? If so, there's one called find_last_of() that returns an index into the string of the last character or string that you send it:

string str(&quot;\\ddata\\conf\\src\\bin\\d_5032.dat&quot;),title;
string::size_type idxslash,idxdot;

idxslash=str.find_last_of('\\');
if (idxslash==str.npos)
idxslash=0;// couldn't find a '\', start at 0
else
++idxslash; // go to next character after last '\'

idxdot=str.find_last_of('.');
if (idxdot==str.npos)
idxdot=str.size(); // couldn't find a '.', go to end

// Extract title (between last '/' and last '.')
title=str.substr(idxslash,idxdot-idxslash);
 
You could also use the windows API function:
Code:
void _splitpath(const char *path, char *drive, char *dir, char *fname, char *ext)
in
Code:
<stdlib.h>
. For (my) convenience I use this in a C++ wrapper and return
Code:
std::string
values. One also needs to use the
Code:
char *_getcwd(char *buffer, int maxlen)
if you are interested in the path name of a file in the current directory.
 
Status
Not open for further replies.
Back
Top