-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils_string.c
125 lines (114 loc) · 2.32 KB
/
utils_string.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
* Copyright (c) 2023 Jeff Huang
*
* License: The MIT License (MIT)
*/
#include "utils_string.h"
char* rtrim_chr(char *str, char c)
{
if (str == NULL || *str == '\0')
{
return str;
}
int len = strlen(str);
char *p = str + len - 1;
while (p >= str && c == *p)
{
*p = '\0';
--p;
}
return str;
}
char* ltrim_chr(char *str, char c)
{
if (str == NULL || *str == '\0')
{
return str;
}
int len = 0;
char *p = str;
while (*p != '\0' && c == *p)
{
++p;
++len;
}
memmove(str, p, strlen(str) - len + 1);
return str;
}
char* trim_chr(char *str, char c)
{
str = rtrim_chr(str, c);
str = ltrim_chr(str, c);
return str;
}
char* rtrim(char *str)
{
if (str == NULL || *str == '\0')
{
return str;
}
int len = strlen(str);
char *p = str + len - 1;
while (p >= str && isspace(*p))
{
*p = '\0';
--p;
}
return str;
}
char* ltrim(char *str)
{
if (str == NULL || *str == '\0')
{
return str;
}
int len = 0;
char *p = str;
while (*p != '\0' && isspace(*p))
{
++p;
++len;
}
memmove(str, p, strlen(str) - len + 1);
return str;
}
char* trim(char *str)
{
str = rtrim(str);
str = ltrim(str);
return str;
}
void delete_char(char* str, char c)
{
int i, j;
for(i = 0, j = 0; str[i] != '\0'; i++)
{
if(str[i] != c){
str[j] = str[i]; j++;
}
}
str[j] = '\0';
}
char* move_char(char* strbuf, size_t start,
int move_bytes, bool backward)
{
size_t new_size;
size_t org_size = strlen(strbuf);
if(backward) {
new_size = strlen(strbuf) + move_bytes;
for(size_t i=org_size; i>=start; i--) {
strbuf[i + move_bytes] = strbuf[i];
strbuf[i] = ' ';
}
trim_chr(strbuf, '\n');
return strbuf;
}
new_size = strlen(strbuf) - move_bytes;
for(size_t i=start; i<org_size - start; i++) {
strbuf[i] = strbuf[i + move_bytes];
strbuf[i + move_bytes] = ' ';
}
strbuf[new_size] = '\0';
trim_chr(strbuf, '\n');
return strbuf;
}