基本C++:从字符转换为字符串
Basic C++: convert from char to string
我对类代码有点困惑。以下是我要做的:
//Program takes "string text" and compares it to "string remove". Any letters in
//common between the two get deleted and the remaining string gets returned.
#include <string>
#include "genlib.h"
string CensorString1(string text, string remove);
int main() {
CensorString1("abcdef", "abc");
return 0;
}
string CensorString1(string text, string remove) {
for (int i = 0; text[i]; i++){
for (int n = 0; remove[n]; n++){
if (i != n){
string outputString = ' '; //to store non repeated chars in,
//forming my return string
outputString += i;
}
}
}
return outputString;
}
- 我在"outputString+=1"上得到一个错误,说:"无法从"char"转换为"std::basic_string
- 我还在"return outputString"中得到一个错误,它说:未声明的标识符
我知道我把一个"char"放在一个"string"变量上,但如果这个"char"很快就会变成一个字符串呢?有办法通过这个吗?
我总是忘记图书馆。有人能推荐几个我应该经常考虑的标准/基本库吗?现在我在想,"genlib.h"(来自课堂)。
C++太让我头疼了,我无法避开不断出现的小错误。告诉我情况会好转的。
您的代码中有许多错误:
- 您的
outputString
需要在外部范围内(语法) - 比较
i
和n
,而不是text[i]
和remove[n]
(语义) - 您正在向输出中添加
i
,而不是text[i]
(语义) - 忽略
CensorString1
(语义)的返回
这是您修改后的代码:
string CensorString1(string text, string remove) {
string outputString;
for (int i = 0; text[i] ; i++){
for (int n = 0; remove[n] ; n++){
if (text[i] != remove[n]){
outputString += text[i];
}
}
}
return outputString;
}
这还有一些遗留问题。例如,使用text[i]
和remove[n]
作为终止条件。它的效率也很低,但这应该是一个不错的开始。
无论如何,字符串在C和C++中总是双引号。单引号常量是字符常量。解决这个问题,你可能会没事的。
另外,看看这个SO问题:如何在C++中向字符串附加int?
祝你在斯坦福大学好运!
这里有一些问题:
string outputString = ' ';
将尝试从char
构造string
,但您不能这样做。不过,您可以将char
分配给string
,因此这应该是有效的:
string outputString;
outputString = ' ';
然后,outputString
仅在if
中可见,因此它不会充当累加器,而是被创建和销毁。
您还试图将字符索引添加到字符串中,而不是字符,我认为这不是您想要做的。看起来你把C和C++搞混了。
例如,如果您想打印字符串的字符,可以执行以下操作:
string s("Test");
for (int i=0;i<s.length();i++)
cout << s[i];
最后,我想说的是,如果您想删除text
中也出现在remove
中的字符,那么在将其添加到输出字符串之前,您需要确保remove
中的任何字符都与当前字符不匹配。
这是我认为您想要的实现,您的代码有多个问题,这些问题刚刚在多个其他答案中描述。
std::string CensorString1(std::string text, std::string remove) {
std::string result;
for (int i = 0; i<text.length(); i++) {
const char ch = text[i];
if(remove.find(ch) == -1)
result.append(1,ch);
}
return result;
}
相关文章:
- wcstombs_s(),转换字符串的长度
- 使用 CStringW/CStringA 和 CT2W/CT2A 转换字符串有什么区别?
- 无法转换字符串插入函数的参数
- 转换字符串向量:基于先前的值跳过元素
- 从中间器转换字符串不起作用,出了什么问题?
- 失败的证明转换字符串到枚举类
- 如何使用正则表达式和提升转换迭代器标记和转换 c 字符串
- 使用java jni时转换字符串类型
- 如何避免在转换字符串令牌流时重复istringstream构造
- 阿托伊未正确转换字符串
- C++,转换字符串,使连续下划线序列变为单个下划线
- 使用长算术转换字符串
- 转换字符串十进制数时的精度
- 将词法转换字符串提升为双精度
- 使用marshal_as函数转换字符串的性能
- C++不会从数据转换字符串
- 无论如何,在c++ /Qt中转换字符串到结构中的字段
- C++ 隐式类型转换字符串 -> int?
- 转换字符串到浮点数,c++实现
- 用于转换字符串大小写的函数