c++c++builder-6

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


I tried to remove a symbol, it works, but I can't find a way to remove specific words.

Is there a way someone can teach me how to find and replace a word with spaces?

Someone please show me what I am doing wrong.

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

Solution

  • Try something more like this:

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

    However, StringReplace() will loop over the string each time, so if you want to stick with a single manual loop, try something more like this instead:

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