如何在文本行中查找和替换单词

时间:2018-12-07 03:36:30

标签: c++ c++builder-6

我试图删除一个符号,它可以工作,但是我找不到删除特定单词的方法。

有人可以教我如何用空格查找和替换单词吗?

有人请告诉我我做错了。

String TfrmMain::GetCorrectCardName(String Str)
{
    String Name = "";
    String Name_Before = Str;
    String NewName = "";


    //Change the name symbols.
    for(int Name_no = 0; Name_no < Name_Before.Length(); Name_no++)
    {
        NewName = Name_Before[Name_no];
        if(Name_Before.c_str()[Name_no] == '@'||Name_Before.c_str([Name_no] == '\\' 
            || Name_Before.c_str()[Name_no] == '#')
        {
            Name += '/';
        }
        else if(Name_Before.c_str()[Name_no] == '_')
        {
            Name += ' ';
        }
        else if(Name_Before.c_str()[Name_no] == '\'')
        {
            Name += '\'';
        }

        // The error starts here  
        else if (NewName == "*Name")
        {
            Name_Before.Insert("         ",Name_no);
            Name = Name_Before;
            Name_Before++; // Keep the numbers right.
            Name_no++; // Same ^
        }
        // end here 

        else
        {
            Name += Name_Before.c_str()[Name_no];
        }
    }
    return Name;
}

1 个答案:

答案 0 :(得分:0)

尝试更多类似的方法:

String TfrmMain::GetCorrectCardName(String Str)
{
    const TReplaceFlags flags = TReplaceFlags() << rfReplaceAll;

    String Name = StringReplace(Str, "@", "/", flags);
    Name = StringReplace(Name, "\\", "/", flags); 
    Name = StringReplace(Name, "#", "/", flags); 
    Name = StringReplace(Name, "_", " ", flags); 
    Name = StringReplace(Name, "*Name", "         ", flags); 

    return Name; 
}

但是,StringReplace()每次都会在字符串上循环,因此,如果您想坚持一个手动循环,请尝试以下类似操作:

String TfrmMain::GetCorrectCardName(String Str)
{
    String Name;

    for(int Name_no = 1; Name_no <= Str.Length(); ++Name_no)
    {
        switch (Str[Name_no])
        {
            case '@':
            case '\\'
            case '#':
                Name += '/';
                break;

            case '_':
                Name += ' ';
                break;

            case '*':
                if (Str.SubString(Name_no+1, 4) == "Name")
                {
                    Name += "         ";
                    Name_no += 4; // Keep the numbers right.
                    break;
                }
                // fall through to next case

            default:
                Name += Str[Name_no];
                break;
        }
    }

    return Name;
}