zoukankan      html  css  js  c++  java
  • 华为招聘机试整理10:实现字符串中子字符串的替换

    华为招聘机试整理10:实现字符串中子字符串的替换

    题目:子字符串的替换
    编写一个字符串替换函数。如函数名为 StrReplace(char* strSrc, char* strFind, char* strReplace)。strSrc为原字符串,strFind是待替换的字符串。strReplace为替换字符串。


    举个直观的样例吧。如:“ABCDEFGHIJKLMNOPQRSTUVWXYZ”这个字符串,把当中的“RST”替换为“ggg”这个字符串。结果就变成了:
    ABCDEFGHIJKLMNOPQgggUVWXYZ
    *题目分析:
    这道题主要是考察怎样在一个非常长的字符串中去寻找目标子字符串,而且进行替换,这个用字符数组或者指针都非常好完毕。
    算法思路:
    ①对长字符串进行循环。找出目标子字符串的首字符位置
    ②对目标子字符长度进行循环,找出目标子字符的尾字符。
    ③用替换字符一一替换。

    ==========================================================================
    參考代码:

    //子字符串的替换.cpp
    //2014.7.11 hepanhui
    #include <iostream>
    #include <string>
    const int maxn = 100;
    using namespace std;
    
    void StrReplace(char* strSrc, char* strFind,char* strReplace)
    {
        int len1 = strlen(strSrc);
        int len2 = strlen(strFind);
        for(int i = 0; i < len1; i++)
        {
            if(strSrc[i] == strFind[0])
            {
                for(int j = 0; j < len2; j++)
                {
                    if(strSrc[i + j] == strFind[j])
                    {
                        strSrc[i + j] = strReplace[j];
                    }
                }
            }
        }
    }
    
    int main()
    {
        char strSrc[maxn];
        char strFind[maxn];
        char strReplace[maxn];
    
        cin >> strSrc >> strFind >> strReplace;
        StrReplace(strSrc, strFind,strReplace);
        cout << strSrc << endl;
        return 0;
    }
    
  • 相关阅读:
    office的高级应用
    python基础
    maven 资源导出失败问题
    单向环形链表和约瑟夫问题
    JDBC连接MySQL
    环形队列
    稀疏数组
    数据库锁机制和事务隔离级别总结
    context的简单应用
    JDBC基本使用方法
  • 原文地址:https://www.cnblogs.com/lytwajue/p/7189900.html
Copyright © 2011-2022 走看看