字符串替换, src 源字符串, buf_size 缓冲大小, search搜索的字符串大小, repstr 需要替换成的字符串
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 |
int str_replace( char
*src, unsigned int
buf_size, char * search, char
*repstr) { if (!src || !search || !repstr|| buf_size < 0) { return
-1; } const
unsigned int
size = buf_size + 1024 ; char
* temp = ( char
*) malloc (size); memset (temp, 0x00, size); char
* src_pos = src; char
* result = src; char
* dst_pos = temp; unsigned int
length = 0; int
search_len = strlen (search); int
rep_len = strlen (repstr); do { src_pos = strstr (src_pos, search); if (!src_pos) { strcpy (dst_pos, result); length += search_len; break ; } strncpy (dst_pos, result, src_pos - result); dst_pos += src_pos - result; //replace strcat (dst_pos, repstr); dst_pos += rep_len; length += src_pos - result + rep_len; src_pos += search_len; result = src_pos; } while (src_pos); if (length >= buf_size) { free (temp); temp = NULL; return
-1; } else { _snprintf_c(src,buf_size, "%s" , temp); free (temp); temp = NULL; return
0; } } int
main( void ) { char
buf[512] ={ "123%4235%%6723" }; printf ( "%s\n" , buf); str_replace(buf,512, "%" , "love" ); printf ( "%s\n" , buf); return
0; } |
结果输出:
123%4235%%6723
123love4235lovelove6723
str_replace字符串替换,码迷,mamicode.com
原文地址:http://www.cnblogs.com/iclk/p/3699856.html