NO

Author Topic: An easy mode to split string  (Read 2020 times)

Alessio

  • Guest
An easy mode to split string
« on: August 23, 2007, 09:44:39 am »
Hi,

I've written a small code to split a weblink string.
I use it to download a file from web using winsock library.

There's a better way to do this ?

Code: [Select]
//
#include <windows.h>
#include <stdio.h>

//
int main(int argc, char* argv[])
{
//
LPCSTR szWebLink = "www.google.it/images/firefox/google.gif";

// GET SITE AND FOLDER PATH
LPSTR p = strchr(szWebLink, '/');
INT iSiteLength = (p-szWebLink)+1;
INT iFilePathLength = lstrlen(p)+1;

CHAR szSite[iSiteLength];
CHAR szFilePath[iFilePathLength];
ZeroMemory(&szSite, iSiteLength);
ZeroMemory(&szFilePath, iFilePathLength);

lstrcpyn(szSite, szWebLink, iSiteLength);
lstrcpy(szFilePath, p);

// GET FILE NAME
p = strrchr(szWebLink, '/');
INT iFileNameLength = lstrlen(p)+1;

CHAR szFileName[iFileNameLength];
ZeroMemory(&szFileName, iFileNameLength);

lstrcpy(szFileName, p);

//
printf("full weblink: %s\n", szWebLink);
printf("site: %s\n", szSite);
printf("filepath: %s\n", szFilePath);
printf("filename: %s\n", szFileName);


//
return 0;
}


Thanks!

Offline JohnF

  • Member
  • *
  • Posts: 1114
    • http://www.johnfindlay.plus.com/
Re: An easy mode to split string
« Reply #1 on: August 23, 2007, 02:37:12 pm »
There might be a Windows API to do that but I'm not sure. Anyway your code is ok. Here is a slightly more compact version.

Code: [Select]
CHAR szSite[MAX_PATH];
CHAR szFilePath[MAX_PATH];
CHAR szFileName[MAX_PATH];
LPCSTR szWebLink = "www.google.it/images/firefox/google.gif";

CHAR * p = strchr(szWebLink, '/');
lstrcpyn(szSite, szWebLink, p - szWebLink + 1);
lstrcpy(szFilePath, strchr(szWebLink, '/'));
lstrcpy(szFileName, strrchr(szWebLink, '/'));

printf("full weblink: %s\n", szWebLink);
printf("site: %s\n", szSite);
printf("filepath: %s\n", szFilePath);
printf("filename: %s\n", szFileName);

John

Alessio

  • Guest
Re: An easy mode to split string
« Reply #2 on: August 23, 2007, 03:38:15 pm »
Thank you! Nice optimization!