SDDSlib
Loading...
Searching...
No Matches
replace_chars.c File Reference

Provides functionality to map one set of characters into another within strings. More...

#include "mdb.h"
#include <ctype.h>

Go to the source code of this file.

Functions

char * replace_chars (char *s, char *from, char *to)
 Maps one set of characters to another in a given string.
 

Detailed Description

Provides functionality to map one set of characters into another within strings.

License
This file is distributed under the terms of the Software License Agreement found in the file LICENSE included with this distribution.
Author
M. Borland, C. Saunders, R. Soliday

Definition in file replace_chars.c.

Function Documentation

◆ replace_chars()

char * replace_chars ( char * s,
char * from,
char * to )

Maps one set of characters to another in a given string.

This function replaces each character in the string s that appears in the from string with the corresponding character in the to string. If the to string is shorter than the from string, it pads the to string with spaces. Similarly, if the from string is shorter than the to string, it pads the from string with spaces.

Parameters
sThe string to be modified.
fromThe set of characters to be replaced.
toThe set of characters to replace with.
Returns
The modified string s with characters replaced.

Definition at line 32 of file replace_chars.c.

33{
34 long lt, lf;
35 char *ptr, *ptr_to, *ptr_from;
36
37 if ((lt = strlen(to)) < (lf = strlen(from))) {
38 char *to_temp;
39 to_temp = tmalloc(sizeof(*to_temp) * (lf + 1));
40 strcpy_ss(to_temp, to);
41 for (; lt < lf; lt++)
42 to_temp[lt] = ' ';
43 to_temp[lf] = 0;
44 } else if (lt > lf) {
45 char *from_temp;
46 from_temp = tmalloc(sizeof(*from_temp) * (lt + 1));
47 strcpy_ss(from_temp, from);
48 for (; lf < lt; lf++)
49 from_temp[lf] = ' ';
50 from_temp[lt] = 0;
51 }
52
53 ptr = s;
54 while (*ptr) {
55 ptr_to = to;
56 ptr_from = from;
57 while (*ptr_from)
58 if (*ptr_from != *ptr) {
59 ptr_from++;
60 ptr_to++;
61 } else {
62 *ptr = *ptr_to;
63 break;
64 }
65 ptr++;
66 }
67 return (s);
68}
void * tmalloc(uint64_t size_of_block)
Allocates a memory block of the specified size with zero initialization.
Definition array.c:59
char * strcpy_ss(char *dest, const char *src)
Safely copies a string, handling memory overlap.
Definition str_copy.c:34