The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > High Level Programming
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #3 (permalink)  
Old 08-21-2008
redoubtable redoubtable is offline
Registered User
  
 

Join Date: Aug 2008
Location: Portugal
Posts: 242
There are actually many ways in which you can do this.

The first problem is the size of your string (char array). You can either use a fixed length array with a bound which you expect won't be exceeded (512 bytes for example) or you can work with dynamic length memory (malloc()/calloc()). I would advise you to use malloc() only as a last resort because it's slower/harder to maintain/prone to human error.

The second problem is choosing the appropriate way of doing the substitution. If you're replacing characters of the same size you could just do it directly like
Code:
char * p;
if ((p = strstr (array, "isthetime")) != NULL)
    strncpy (p, "new chars", strlen ("new chars"));
and it should cause no problem. On the other hand if you're replacing characters with different lengths say "AAA" for "AAAA" you must have in mind that the substitution will overwrite one element in the array. If you wish to keep that element you must copy the array into a temporary array and then strncpy() it back to the original array after the replacing takes place.

You're third problem is having much caution with the terminating byte '\0' in your array. If you're not careful enough you might overwrite it and forget to replace it which in turn could lead to unexpected conditions.

PS: you can also use regcomp() and regexec() for pattern matching/replacing.