Удалить из S первое вхождение комбинации «красный»

У меня проблемы с переписыванием кода в формат Builder c ++ 6.
Итак, задачи следующие:

  1. Удалить из S первое вхождение комбинации «красный»
  2. После первой комбинации ‘th’ вставить ‘e’
  3. Скопируйте 5 символов в Х из S и вставьте их после 6-го члена (есть проблемы с решением)
  4. Удалить все «.» и «,» из S

    void __fastcall TForm1::Button1Click(TObject *Sender)
    {
    AnsiString S = Edit1->Text;
    AnsiString X = Edit2->Text;
    string str;
    
    //Delete from S first occurrence of a combination of 'red'
    str = "red";
    std::size_t pos = S.find(str);
    if(pos != std::string::npos){
    S.replace(pos, str.length(), "");
    }
    
    //After first combination 'th' paste 'e'
    str = "th";
    pos = S.find(str);
    if(pos != std::string::npos){
    S.insert(pos + str.length(), "e");
    }
    
    //Copy 5 symbols to Х from S and paste them after the 6th member
    str = 6;
    pos = S.find(str);
    if(pos != std::string::npos){
    X = S.substr(pos + str.length(), 5);
    }
    
    //Delete all points and comas
    for(int i=1;i<s.Length();i++){
    if(s[i]=='.')s.Delete(i,1);
    }
    for(int i=1;i<s.Length();i++){
    if(s[i]==',')s.Delete(i,1);
    }
    Label1->Caption=S;
    Label2->Caption=X;
    }
    

0

Решение

Вы смешиваете AnsiString а также std::string логика вместе (или, возможно, вы мигрируете из std::string и не знаю, как переписать для AnsiString?). find(), replace(), insert(), length(), а также substr() являются все std::string методы. AnsiString эквиваленты Pos(), Delete(), Insert(), Length(), а также SubString(),

Нет смысла смешивать два типа строк в одной и той же функции. Выберите один или другой.

Кроме того, ваши два цикла для удаления точек / запятых нарушены. Вы игнорируете последний символ в строке и пропускаете символ каждый раз, когда удаляете символ. Итак, либо исправьте циклы, либо вы можете просто заменить их на C ++ Builder StringReplace() функция вместо

Если вы хотите повторно использовать свой существующий std::stringна основе кода, вы можете сделать это. Вам не нужно использовать AnsiString:

#include <string>

void __fastcall TForm1::Button1Click(TObject *Sender)
{
std::string S = Edit1->Text.c_str();
std::string X = Edit2->Text.c_str();
std::string str;

//Delete from S first occurrence of a combination of 'red'
str = "red";
std::size_t pos = S.find(str);
if (pos != std::string::npos){
S.replace(pos, str.length(), "");
}

//After first combination 'th' paste 'e'
str = "th";
pos = S.find(str);
if (pos != std::string::npos){
S.insert(pos + str.length(), "e");
}

//Copy 5 symbols to Х from S and paste them after the 6th member
str = "6";
pos = S.find(str);
if (pos != std::string::npos){
X = S.substr(pos + str.length(), 5);
}

//Delete all points and comas
pos = S.find_first_of(".,");
while (pos != std::string::npos) {
s.erase(pos, 1);
pos = S.find_first_of(".,", pos);
}

Label1->Caption = S.c_str();
Label2->Caption = X.c_str();
}

Однако, поскольку вы взаимодействуете с компонентами VCL, возможно, имеет смысл переписать код для использования AnsiString вместо (или лучше, System::Stringна случай, если вы когда-нибудь перенесете код в современный Версия C ++ Builder):

void __fastcall TForm1::Button1Click(TObject *Sender)
{
System::String S = Edit1->Text;
System::String X = Edit2->Text;
System::String str;

//Delete from S first occurrence of a combination of 'red'
str = "red";
int pos = S.Pos(str);
if (pos != 0) {
S.Delete(pos, str.Length());
}

//After first combination 'th' paste 'e'
str = "th";
pos = S.Pos(str);
if (pos != 0) {
S.Insert(pos + str.Length(), "e");
}

//Copy 5 symbols to Х from S and paste them after the 6th member
str = 6;
pos = S.Pos(str);
if (pos != 0) {
X = S.SubString(pos + str.Length(), 5);
}

//Delete all points and comas
S = StringReplace(S, ".", "", TReplaceFlags() << rfReplaceAll);
S = StringReplace(S, ",", "", TReplaceFlags() << rfReplaceAll);

Label1->Caption = S;
Label2->Caption = X;
}
0

Другие решения


По вопросам рекламы ammmcru@yandex.ru
Adblock
detector