Link to home
Start Free TrialLog in
Avatar of KaranGupta
KaranGupta

asked on

substring for char*

Hi

I have a char* variable

I want to use substring.

I want to know if there is any substring function for char*

Regards
Karan
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

   char s[] = "please help me";
    char s2[5];
    ZeroMemory(s2, 5);
    _tcsncpy(s2, &s[7], 4);


s2 now contains "help"
Or did you want strstr -
Returns a pointer to the first occurrence of a search string in a string.

copied from help files:

// crt_strstr.c

#include <string.h>
#include <stdio.h>

char str[] =    "lazy";
char string[] = "The quick brown dog jumps over the lazy fox";
char fmt1[] =   "         1         2         3         4         5";
char fmt2[] =   "12345678901234567890123456789012345678901234567890";

int main( void )
{
   char *pdest;
   int  result;
   printf( "String to be searched:\n   %s\n", string );
   printf( "   %s\n   %s\n\n", fmt1, fmt2 );
   pdest = strstr( string, str );
   result = (int)(pdest - string + 1);
   if ( pdest != NULL )
      printf( "%s found at position %d\n", str, result );
   else
      printf( "%s not found\n", str );
}
Avatar of KaranGupta
KaranGupta

ASKER

Hi Andy

I have tried your first solution

I am getting an error

C2664: 'wcsncpy' : cannot convert parameter 1 from 'char [5]' to 'wchar_t *'      c:\Documents and
Those functions are for char (as you asked for) not for wchar.
Try replacing char with TCHAR in the example I gave (that reverts to char for ASCII and wchar for UNICODE)
Alternatively, if you are working with char strings in a UNICODE app then replace _tcsncpy with strncpy.
Hi Andy

I have tried this code what you gave me in your first post

char s[] = "please help me";
char s2[5];
ZeroMemory(s2, 5);
_tcsncpy(s2, &s[7], 4);

I haven't try anything different

Regards
Karan

ASKER CERTIFIED SOLUTION
Avatar of AndyAinscow
AndyAinscow
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial