Subject: Replace Substrings
From: "Jim Duffy" <[EMAIL PROTECTED]>
Date: Thu, 7 Aug 2003 01:22:18 -0700

Does anyone know a way to search through a string for all instances of a
substring and replace them with a different substring?

For example:

string1 "This[CR]is a [CR] Test"

I need to replace all the "[CR]" with the '\n' newline character..

I've tried using StrStr() and TxtReplaceStr() but these aren't really cut
out for this.  Can't find any other API that might work..

Your example is character replacement, which can be achieved by:


//   substitute Char  c1 with Char c2
Char *ptr = string1;
while ((ptr = StrChr (ptr, c1)) != NULL) {*ptr = c2; ptr++;}

For substring substitution in-situ, you can use:

// Substitute Char *str1 with Char *str2, using shortest length
Char *ptr = string1;
UInt16 len = (StrLen (str1) > StrLen (str2) ? StrLen (str2) : StrLen (str1));
while (len && (ptr = StrStr (ptr, str1)) != NULL) {
        StrNCopy (ptr, str2, len):
        ptr += len;
}

Fully handling substrings of unequal size is a tricker because you have to make a copy of the original string and copy it back to the original string in segments, inserting the new string as appropriate. Someone else provided an example of that.

Roger Stringer
Marietta Systems, Inc.  (www.mariettasystems.com)


-- For information on using the Palm Developer Forums, or to unsubscribe, please see http://www.palmos.com/dev/support/forums/

Reply via email to