【问题标题】:String's character delete & Frequency without using library字符串的字符删除和频率不使用库
【发布时间】:2016-10-15 11:09:06
【问题描述】:

我正在尝试处理需要输入两个字符串 S & str 然后提供三个结果的作业(不使用任何字符串库):

1.确定给定str在S中的number和position

2.Return S 删除任何可能出现的 str

例如。如果 S=aababacd cdefgh , str=aba

频率为2,位置为
字符删除将是 cd cdefgh

附上的代码是我目前做的,我可以输出频率和位置,但是现在我有几个未解决的问题,我不知道如何实现它。

1.一旦我输入了一个带有空格的字符串,例如。 abcd efg,代码将立即实现它,它不会将 abcd efg 视为一个字符串,而是将其视为 S=abcd and str=efg ,这个问题我不能输入一个带空格的字符串进行测试。

2.我怎样才能像这种形式输出位置: ,因为我使用循环输出结果所以不能那样,我在想是否我可以创建一个数组来存储 i 然后 cout 它,但我失败了。

3.关于字符删除问题,我找到了一个similar problem,上面说如果我知道如何使用strcpy而不使用库我会知道,但我学会了,我仍然不知道如何处理这个问题,我知道我可以比较这两个字符串,但我不知道如何在没有 str 部分的情况下输出 S。我想在循环后将 S 更改为 '\0' 并输出,但这是完全错误的。

如果有人能给我一些建议,我将不胜感激,谢谢!

#include <iostream>
#include <algorithm>

using namespace std;

void CharacterDelete(){

    char S[100], str[100];
    bool match =true;

    cout << "Enter string S :";
    cin >> S;
    cout << "Enter string str :";
    cin>>str;

    for(int i=0; S[i]!='\0'; i++)
    {
        for(int j=0; str[j]!='\0';j++){

            if(S[i+j]!=str[j]){

                match=false;
                break;
            }
            if(match){
                S[i+j]='\0';
            }
        }
    }
    cout<<S;//Apparently thats a wrong solution
}

void Frequency(){


    string S,str;
    cout<<"Please input string S"<<endl;
    cin>>S;
    cout<<"Please input string str"<<endl;
    cin>>str;

    int sum=0;


    for (int i=0; i<S.size(); i++)
    {
        if (i + str.size() > S.size()) break;
        bool match=true;
        for (int j=0; j<str.size(); j++)
            if (S[i+j] != str[j])
            {
                match=false;
                break;
        //Once we print blank space and it would implement it immediately?
            }
            if(match)
            {
                sum++;
                cout<<"Start from"<<i<<endl;
                //What if we use an array to store it and then output it?but how to write it?

            }
    }

    cout<<"The Frequency is "<<sum<<endl;
    if(sum==0){
        cout<<"There is no starting point"<<endl;

    }
}

int main() {
    Frequency();
    CharacterDelete();
    return 0;
}

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    您正在使用局部变量 S 和 str。您需要在 main 函数中使用 S 和 str 。然后在 Frequency() 和 CharacterDelete 中从 main 转移这个变量。

    删除字符:创建新变量,然后复制没有删除字符的字符。

    输出:

    cout << "<" << num_word << ", " << number << ">\n";
    

    【讨论】:

    • 谢谢大佬,但是我只想检查一下关于字符部分的事情,你能给我一个关于复制不删除的例子吗,非常感谢
    猜你喜欢
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多