zoukankan      html  css  js  c++  java
  • 字符串替换

    //============================================================================
    // Name : test.cpp
    // Author :
    // Version :
    // Copyright : Your copyright notice
    // Description : Hello World in C++, Ansi-style
    //============================================================================

    #include <iostream>
    using namespace std;

    extern "C"
    {
    #include <errno.h>
    #include <math.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>

    }

    // You must free the result if result is non-NULL.
    char *str_replace(char *orig, char *rep, char *with) {
    char *result; // the return string
    char *ins; // the next insert point
    char *tmp; // varies
    int len_rep; // length of rep
    int len_with; // length of with
    int len_front; // distance between rep and end of last rep
    int count; // number of replacements

    if (!orig)
    return NULL;
    if (!rep || !(len_rep = strlen(rep)))
    return NULL;
    if (!(ins = strstr(orig, rep)))
    return NULL;
    if (!with)
    with = "";
    len_with = strlen(with);

    for (count = 0; tmp = strstr(ins, rep); ++count) {
    ins = tmp + len_rep;
    }

    // first time through the loop, all the variable are set correctly
    // from here on,
    // tmp points to the end of the result string
    // ins points to the next occurrence of rep in orig
    // orig points to the remainder of orig after "end of rep"
    tmp = result = (char *)malloc(strlen(orig) + (len_with - len_rep) * count + 1);

    if (!result)
    return NULL;

    while (count--) {
    ins = strstr(orig, rep);
    len_front = ins - orig;
    tmp = strncpy(tmp, orig, len_front) + len_front;
    tmp = strcpy(tmp, with) + len_with;
    orig += len_front + len_rep; // move to next "end of rep"
    }
    strcpy(tmp, orig);
    return result;
    }

    int main() {
    char *me = "thank you";
    char *result = str_replace(me, "th", "me");
    cout << result << endl; // prints !!!Hello World!!!
    free(result);
    return 0;
    }
  • 相关阅读:
    MVC各部分技术体现
    SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
    my SQL Workbench创建数据库
    哪些素质很重要,却是读书学不来
    给程序员最好的18个忠告!
    互联网协议入门(二)
    互联网协议入门(一)
    div+css命名规范大全
    javascript中this的用法
    XHTML 相对路径与绝对路径
  • 原文地址:https://www.cnblogs.com/wangkangluo1/p/2337700.html
Copyright © 2011-2022 走看看