基本C++:从字符转换为字符串

Basic C++: convert from char to string

本文关键字:转换 字符串 字符 C++ 基本      更新时间:2023-10-16

我对类代码有点困惑。以下是我要做的:

//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;
}
  1. 我在"outputString+=1"上得到一个错误,说:"无法从"char"转换为"std::basic_string
  2. 我还在"return outputString"中得到一个错误,它说:未声明的标识符

我知道我把一个"char"放在一个"string"变量上,但如果这个"char"很快就会变成一个字符串呢?有办法通过这个吗?

我总是忘记图书馆。有人能推荐几个我应该经常考虑的标准/基本库吗?现在我在想,"genlib.h"(来自课堂)。

C++太让我头疼了,我无法避开不断出现的小错误。告诉我情况会好转的。

您的代码中有许多错误:

  • 您的outputString需要在外部范围内(语法)
  • 比较in,而不是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;
}