[KLUG Programming] substr in C?

Bert programming@kalamazoolinux.org
Wed, 23 Jul 2003 09:15:53 +0200


Adam Williams wrote:

>>>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". 
>>>      
>>>
>>ere'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);
>>    
>>
>
>I remember by C instructor telling me that pointer arithmatic was bad
>(like oldstring+5).  But you imply that it is OK?  Was my C instructor
>on crack, or why did he make that statement?
>  
>
I think he made his remark because pointer arithmatic is found to be bad 
programming. In a way he is right. It's the nature of C that allows you 
to fiddle with pointers. (I make often use it this bad behaviour because 
it's easy to program that way.) I can't name any other programming 
language that allows you to add integers to pointers.

As to characters, this arithmetic could fail if you use some other 
character base than 8 bit. A 16 bits base is counted wrong if you use 
string+3 but is counted right if you use string[3].



Bert.