1.一级指针处理字符串的常见方式

如果使用单个指针,不方便对字符串本身进行操作,只适合遍历。

使用两个指针,

两个指针和字符串大致有两个常见处理方式:

(1)两个指针从字符串首部开始向后移动,同时处理字符串。

(2)两个指针分别指向字符串首部和尾部,向中间靠拢。

2.两个指针放在字符串两端

示例:

去除字符串两端的空格。

#include <ctype.h>
#include <string.h>
#include <stdio.h>

void trimSpace(const char *str, char *newStr, int len)
{
    const char *p, *q;
    int len2;
    
    if (NULL == str || NULL == newStr)
        return;

    p = str;
    q = p + strlen(str) - 1;    
    while (p < q && isspace(*p)) ++p;
    while (p < q && isspace(*q)) --q;
    len2 = q - p +1;
    if (len >= len2) {
        memcpy(newStr, p, len2);
        newStr[len2] = 0;
    } else {
        memcpy(newStr, p, len);
        newStr[len] = 0;
    }
    
}


int main()
{
    char str[] = "  abcabc  ";
    char str2[4] = {0};

    trimSpace(str, str2, sizeof(str2) - 1);
    printf("%sn", str2);

    return 0;
}

(2)字符串翻转

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

/* 非递归版本,使用指针放在字符串两端 */ void inverse(char *str) { char *p, *q, tmp; if (NULL == str) return; p = str; q = str + strlen(str) - 1; while (p < q) { tmp = *p; *p = *q; *q = tmp; ++p, --q; } } static void _inverse1(char *str1, char *str2) { if (!*str2) return; _inverse1(str1, str2+1); strncat(str1, str2, 1); } /* 递归版本 */ void inverse1(char *str) { char *tmp = NULL; if (NULL == str) return; if ((tmp = (char *)calloc(strlen(str) + 1, sizeof(char))) == NULL) return; _inverse1(tmp, str); strncpy(str, tmp, strlen(tmp)+1); free(tmp); } int main() { char str[] = "123456"; inverse1(str); printf("%sn", str); return 0; }

 

3.两个指针放在字符串首部

(1)strstr挖字符串

#include <string.h>
#include <stdio.h>

int getCount(const char *str1, const char *str2)
{
    const char *p1 = str1, *p2 = str2;
    int count = 0;
    
    if (NULL == str1 || NULL == str2)
        return -1;
    
    while (str1 = strstr(str1, str2)) {
        count++;
        str1 += strlen(str2);
    }

    return count;
}

int main()
{
    char str[] = "gsadgdasabcadfaabcasdabc";
    char str2[] = "abc";
    int n;

    n = getCount(str, str2);
    printf("%dn", n);

    return 0;
}

(2)去除字符串中的某些字符

去除空格。

old指针的意义是:指向旧的数组,并挖出非空格的字符输出给新数组。

new指针的意义是:指向新的数组,并输入old指针传来的字符。

由于 new 永远不会超过 old 所以,新、旧数组可以使用同样的空间。

#include <ctype.h>
#include <string.h>
#include <stdio.h>

void trimSpace(char *str)
{
    char *new, *old;

    if (NULL == str)
        return;

    new = str;
    old = str;
    while (*old) {
        if (isspace(*old))
            ++old;
        else
            *new++ = *old++;    
    }
    *new = 0;
}

int main()
{
    char str[] = " 12  34  56  78 ";
    
    trimSpace(str);
    printf("%sn", str);

    return 0;
}

4. 总结

如果使用一级指针处理字符串,应该先思考两个一级指针应该放在字符串两端还是一端,然后思考每个指针的实际意义。

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程