AnsiString
とロジックを混在させてstd::string
います (または、から移行しstd::string
ていて、書き直す方法がわからない場合もありAnsiString
ます)。 find()
、replace()
、insert()
、length()
、およびsubstr()
はすべてstd::string
メソッドです。AnsiString
同等のものPos()
は、、、、、およびです。Delete()
Insert()
Length()
SubString()
同じ関数で 2 つの文字列型を混在させる理由はありません。どちらかを選んでください。
また、ピリオド/コンマを削除する 2 つのループが壊れています。文字列の最後の文字を無視していて、文字を削除するたびに文字をスキップしています。したがって、ループを修正するか、StringReplace()
代わりに C++Builder の関数に置き換えることができます。
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;
}