【问题标题】:Concat string in C++(STL)C++(STL)中的连接字符串
【发布时间】:2009-06-11 07:56:26
【问题描述】:

我有这样的代码

string xml_path(conf("CONFIG"));

xml_path+=FILE_NAME;

在哪里, conf 函数返回char *,文件名是const char *

我想把它合并成一行

xml_path(conf("CONFIG")).append(FILE_NAME) 

我该怎么做?

有什么建议吗??

【问题讨论】:

  • 每个人都错过了您要求单线解决方案的事实。 (但你为什么想要那个?)
  • 假设我想连接 5 个字符串然后我可以做到 .append().append() 我不需要像在 java StringBuffer 中那样做 5 个步骤 obj = new StringBuffer("foobar" ).append("foo").append("bar");

标签: c++ string stl


【解决方案1】:

问了一行:

string xml_path = string(conf("CONFIG")) + string(FILE_NAME);

(我假设xml_path 是变量的名称,而不是我不知道的库中的某种调用)。

【讨论】:

    【解决方案2】:

    或者,如果您想格式化不同类型的变量,请使用 ostringstream。

    例如。

    std::ostringstream oss; 
    int a = 2; 
    char *s = "sometext"; 
    oss<<s<<a<<endl; 
    cout<<oss.str(); // will output "sometext2"
    

    【讨论】:

      【解决方案3】:
      const char * f = "foo";
      char * b = "bar";
      
      string s = string( f ) + b;
      

      请注意,您不能使用 append(-0,因为涉及的字符串都不是 std:;string。如果您真的要追加,则必须是两阶段过程:

      string s ( f );
      s.append( b );
      

      【讨论】:

        【解决方案4】:
        string xml_path(conf("CONFIG"));
        xml_path += string(FILE_NAME);
        

        应该可以解决问题。

        【讨论】:

          猜你喜欢
          • 2018-03-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多