- 论坛徽章:
- 2
|
给个通用的函数,并附例子。
- /* nstrcovt.c */
- #include <string.h>
- int nstr_get_nchar(const char *s, int off, int lmt)
- {
- if (off < lmt) {
- if (s[off] < 0 && off + 1 < lmt) {
- return 2;
- }
- return 1;
- }
- return 0;
- }
- int nchar_match(const char *c, int c_len, const char *list, int list_len)
- {
- int i;
- int len;
- for (i = 0; i + c_len <= list_len; i += len) {
- len = nstr_get_nchar(list, i, list_len);
- if (len == c_len && strncmp(c, list + i, len) == 0) {
- return i;
- }
- }
- return -1;
- }
- int nstr_convert(char *s, int off, int lmt, const char *src, const char *tar)
- {
- int c_len;
- int i;
- int src_len;
- src_len = strlen(src);
- for (; off < lmt; off += c_len) {
- c_len = nstr_get_nchar(s, off, lmt);
- i = nchar_match(s + off, c_len, src, src_len);
- if (i != -1) {
- strncpy(s + off, tar + i, c_len);
- }
- }
- return 0;
- }
- /* test */
- #if 1
- #include <stdio.h>
- int main(void)
- {
- char str[] = "abcdefghijklmnopqrstuvwxyzавс";
- char rep[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZАВС";
- char buf[] = "I LIKE АВС";
- nstr_convert(buf, 0, strlen(buf), rep, str);
- puts(buf);
- return 0;
- }
- #endif
复制代码 |
|