![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| High Level Programming Post questions about C, C++, Java, SQL, and other programming languages here. |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Substituting variables from external files | oneillc9 | Shell Programming and Scripting | 1 | 07-31-2008 03:12 PM |
| substituting | neyo | Shell Programming and Scripting | 1 | 03-08-2008 10:08 AM |
| Substituting with value of variable in Sed | jyotipg | Shell Programming and Scripting | 1 | 09-26-2006 09:54 AM |
| Substituting variable with current time | jhansrod | Shell Programming and Scripting | 4 | 11-20-2005 08:20 PM |
| substituting shell variables | suds19 | Shell Programming and Scripting | 1 | 10-16-2002 08:55 AM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
||||
|
substituting one string for another
I have a Linux C program I'm writing that has one section where, within a large string, I need to substitute a smaller string for another, and those probably won't be the same size.
For instance, if I have a string: "Nowisthetimeforallgoodmen" and I want to substitute 'most' for 'all' the main string will increase in size: "Nowisthetimeformostgoodmen" or a substitution that will increase the size of the main string: "Nowisthetimefornogoodmen" I thought I might get some opinions about what might be the best approach on something like this, besides some more cumbersome way of doing it. I've been looking at the C string functions to see if there's one that might be helpful, but I don't really see any. Any help would be appreciated. |
|
||||
|
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"));
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. |
| Sponsored Links | ||
|
|