您正在将逻辑混合在一起(或者您正在迁移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;
}