SDDSlib
Loading...
Searching...
No Matches
strslide.c
Go to the documentation of this file.
1/**
2 * @file strslide.c
3 * @brief Implements the strslide function.
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
18/**
19 * @brief Slides character data within a string by a specified distance.
20 *
21 * This function shifts the characters in the string `s` by the given `distance`.
22 * A positive distance slides characters toward higher indices (to the right),
23 * while a negative distance slides characters toward lower indices (to the left).
24 *
25 * @param s Pointer to the null-terminated string to be modified.
26 * @param distance The number of positions to slide the string. Positive values
27 * shift characters to the right, and negative values shift
28 * characters to the left.
29 * @return Returns the modified string `s` on success. Returns `NULL` if the
30 * distance is greater than the string length when sliding to higher indices.
31 */
32char *strslide(char *s, long distance) {
33 char *source, *target;
34 long i, length;
35
36 if (!s || !distance)
37 return s;
38 if (distance > 0) {
39 /* slide toward higher index */
40 source = s + (length = strlen(s));
41 if (distance > length)
42 return NULL;
43 target = source + distance;
44 for (i = length; i >= 0; i--)
45 *target-- = *source--;
46 } else if (distance < 0) {
47 /* slide toward lower index */
48 length = strlen(s);
49 if ((distance = -distance) >= length)
50 *s = 0;
51 else {
52 source = s + distance;
53 target = s;
54 do {
55 *target++ = *source++;
56 } while (*source);
57 *target = 0;
58 }
59 }
60 return s;
61}
char * strslide(char *s, long distance)
Slides character data within a string by a specified distance.
Definition strslide.c:32