SDDSlib
Loading...
Searching...
No Matches
replace_chars.c
Go to the documentation of this file.
1/**
2 * @file replace_chars.c
3 * @brief Provides functionality to map one set of characters into another within strings.
4 *
5 * @copyright
6 * - (c) 2002 The University of Chicago, as Operator of Argonne National Laboratory.
7 * - (c) 2002 The Regents of the University of California, as Operator of Los Alamos National Laboratory.
8 *
9 * @license
10 * This file is distributed under the terms of the Software License Agreement
11 * found in the file LICENSE included with this distribution.
12 *
13 * @author M. Borland, C. Saunders, R. Soliday
14 */
15
16#include "mdb.h"
17#include <ctype.h>
18
19/**
20 * @brief Maps one set of characters to another in a given string.
21 *
22 * This function replaces each character in the string `s` that appears in the `from` string
23 * with the corresponding character in the `to` string. If the `to` string is shorter than
24 * the `from` string, it pads the `to` string with spaces. Similarly, if the `from` string
25 * is shorter than the `to` string, it pads the `from` string with spaces.
26 *
27 * @param s The string to be modified.
28 * @param from The set of characters to be replaced.
29 * @param to The set of characters to replace with.
30 * @return The modified string `s` with characters replaced.
31 */
32char *replace_chars(s, from, to) char *s, *from, *to;
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 * replace_chars(char *s, char *from, char *to)
Maps one set of characters to another in a given string.
char * strcpy_ss(char *dest, const char *src)
Safely copies a string, handling memory overlap.
Definition str_copy.c:34