PDA

Click to See Complete Forum and Search --> : How do I search and replace a character in a string


abdul
Aug 4th, 2001, 10:36 AM
let us say, I have a string:

\folder\file.html

How do I search the all the caracters "\" and replace then with "\\" SO I get a string like this:

\\folder\\file.html


I know it is straightforward for you guys!
;)

parksie
Aug 4th, 2001, 11:13 AM
bool StringFind(string sSearchIn, string sSearchFor, uint &nPos) {
uint nTemp = sSearchIn.find(sSearchFor);
if(nTemp < sSearchIn.length()) {
nPos = nTemp;
return true;
}

return false;
}

bool Replace(string &sLine, string sReplaceWhat, string sReplaceWith) {
uint nPos = 0;
uint i = 0;
while (StringFind(sLine, sReplaceWhat, nPos)) {
sLine = sLine.replace(nPos, sReplaceWhat.length(), sReplaceWith);
i++;
}
if(i) return true; return false;
}Then just use:string x = "c:\\filename\\path.ext"
Replace(x, "\\", "\\\\");Not sure why you'd want to do this though :) PS: "\\" is actually only "\" because \ is an escape character.

abdul
Aug 4th, 2001, 11:40 AM
Actually, when you are working with the directories, you divide the directories with "\\" right?

But I get the response from the client with the directories divided with "\". So I want to convert "\" to "\\"

parksie
Aug 4th, 2001, 11:46 AM
No. Path separators are always '\'. But you have to type \\ in the source code because the preprocessor (or is it the compiler? can't remember...) uses '\' as an escape character. Therefore to include it in a literal string you need to use '\\'. :)

abdul
Aug 4th, 2001, 02:23 PM
Sorry for this late post:(

But,then, how do I know if a file exists or not? I have tried the following code but whenever I type the wrong address in the browser, the compiler gives me an assertion error message.

This code should redirect the client to error.html page if the address is wrong. But if the file exists that it should use the given file.

d=recv(wparam,aa,1000,0);
abc(aa);
p=aa + 4;
e=0;
while(*p!=32)
{
if (*p=='/')
{
buf[e]='\\';
}
else
buf[e]=*p;
if(buf[e]=='.')
fn=1;
p++;
e++;
}

buf[e] = 0;

if (strlen(buf)==1)
strcpy(filename,"c:\\website\\woo\\index.html");
else
{

strcpy(filename,"c:\\website");

strcpy(checkfilename, filename);
strcat(checkfilename, buf);

if(access(filename, 0) == -1){
strcpy(filename,"c:\\website\\woo\\error.html");
}
else{MessageBox(NULL, checkfilename, "DF",MB_OK);
strcat(filename,buf);
}

if(fn==0)

{
strcat(filename,"index.html");
}

}
abc(filename);


fp=fopen(filename,"rb");
fseek(fp,0,2);
size=ftell(fp);

strcpy(header,"HTTP/1.0 200 ok \r\n");

sprintf(bb,"Content-Length:%ld\r\n\r\n",size);
strcat(header,bb);
send(wparam,header,strlen(header),0);
pp= (char*)GlobalAlloc(GPTR, size);
fseek(fp,0,0);
fread(pp,size,1,fp);
send(wparam,pp,size,0);
closesocket(wparam);
GlobalFree(pp);


Can you please check what is wrong in there again. All the variables are declared first

:confused: