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

How do I find and replace a word in a text line

我尝试删除一个符号,它有效,但我找不到删除特定单词的方法。

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

有人请告诉我我做错了什么。

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;
}

试试像这样的东西:

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;
}