Jump to content

string copy

- - - - -

  • Please log in to reply
3 replies to this topic

#1
yangss

yangss

    Newbie

  • Members
  • Pip
  • 6 posts
if i have an input which is a string, how do i copy some of the string value from the string? For example 1+5-(2*3)+9, i wan to copy (2*3) from this string, how to do that?

#2
zoranh

zoranh

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 207 posts
Use strncpy function (read the warning on this page before using it). It gives you the opportunity to specify how many characters to copy, as opposed to strcpy function which only allows you to copy till the end of the source string.

Don't forget to allocate one character more in the destination string for '\0'.

#3
Ancient Dragon

Ancient Dragon

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 400 posts
First you have to locate the substring that you want to copy. strstr() can do that for you. But that probably won't work either because you have to know the characters to be copied, and if you knew that then there would be no need to copy them :)

I think what you really want is to copy everything between the parentheses ( and ). So call strchr() to locate the first ( and then copy everything one character at a time from there up to the closing parentheses. You will need to know how to use pointers to accomplish that.

char line[] = "1+5-(2*3)+9";

char buf[25] = {0};

char *ptr = strchr(line,'(');

char* p2 = buf;

if( ptr != NULL)

{

   while( *ptr && *ptr != ')' )

   {

      *p2++ = *ptr++;

   }

   if( *ptr == ')')

      *p2++ = *ptr;

}


Visit Grandpa's Forums, a social networking forum, with family-oriented arcade games, blogs, discussion forums, and photo albums.

#4
nofolo

nofolo

    Newbie

  • Members
  • Pip
  • 4 posts
thanks for info




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users