[KLUG Programming] substr in C?

Bruce Smith programming@kalamazoolinux.org
21 Jul 2003 13:05:23 -0400


> Is there a C equivalent to substr in perl or PHP? Something that might work 
> like this: 
> 
> oldstring="Tony missed the clue bus.";
> /* start at position 0, give me the next 4 chars as my string */
> newstring=substr(oldstring, 0, 4); 
> 
> newstring would then contain the value "Tony". 

Here's an example that gives you the word "missed" from your string:

------------------------------------------------------------------
#include <stdio.h>
main(argc, argv)
int argc;
char **argv;
{
char *oldstring="Tony missed the clue bus.", newstring[7];
  strncpy(newstring, oldstring+5, 6);
  newstring[6]='\0';
  printf("%s\n%s\n", oldstring, newstring);
}
------------------------------------------------------------------

The word "Tony" is easier since it's at the beginning:
  strncpy(newstring, oldstring, 4);
  newstring[4]='\0';

--------------------------------------------
Bruce Smith                bruce@armintl.com
System Administrator / Network Administrator
Armstrong International, Inc.
Three Rivers, Michigan  49093  USA
http://www.armstrong-intl.com/
--------------------------------------------