上周我有一个作业要写一个函数:该函数获取一个 string
和一个 char
值,并且应该将字符串分为两部分,在现有字符的第一次出现。
代码有效,但我的老师告诉我再做一次,因为代码写得不好。但我不明白如何让它变得更好。到目前为止,我知道用空格定义两个字符串不好,但否则会出现越界异常。由于字符串输入发生变化,因此字符串大小每次都会发生变化。
#include <iostream>
#include <string>
using namespace std;
void divide(char search, string text, string& first_part, string& sec_part)
{
bool firstc = true;
int counter = 0;
for (int i = 0; i < text.size(); i++) {
if (text.at(i) != search && firstc) {
first_part.at(i) = text.at(i);
}
else if (text.at(i) == search&& firstc == true) {
firstc = false;
sec_part.at(counter) = text.at(i);
}
else {
sec_part.at(counter) = text.at(i);
counter++;
}
}
}
int main() {
string text;
string part1=" ";
string part2=" ";
char search_char;
cout << "Please enter text? ";
getline(cin, text);
cout << "Please enter a char: ? ";
cin >> search_char;
divide(search_char,text,aprt1,part2);
cout << "First string: " << part1 <<endl;
cout << "Second string: " << part2 << endl;
system("PAUSE");
return 0;
}
最佳答案
我建议你,学习使用 C++ 标准函数。有很多实用函数可以帮助您编程。
void divide(const std::string& text, char search, std::string& first_part, std::string& sec_part)
{
std::string::const_iterator pos = std::find(text.begin(), text.end(), search);
first_part.append(text, 0, pos - text.begin());
sec_part.append(text, pos - text.begin());
}
int main()
{
std::string text = "thisisfirst";
char search = 'f';
std::string first;
std::string second;
divide(text, search, first, second);
}
这里我使用了std::find
,你可以从 here 中阅读它。还有迭代器
。
您还有其他一些错误。您按值传递文本,每次调用函数时都会进行复制。通过引用传递它,但使用 const
限定它,这将表明它是输入参数而不是输出。
关于c++ - 字符串声明/引用参数的困难 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662780/