【问题标题】:Copying One String To Another Using For Loop [duplicate]使用 For 循环将一个字符串复制到另一个字符串
【发布时间】:2020-03-28 05:06:25
【问题描述】:

为什么即使在运行循环以从 s 中复制字符之后,临时字符串的大小仍为 0?我得到 0 作为临时字符串的大小。

#include <iostream>
#include<string>
using namespace std;

string CopyString(string s,int delta,int len){
   string temp;
    int i;
    for (i = 0; i < len; i++)
    {
        temp[i] = s[i + delta];
    }

    cout<<temp.size(); 
    return temp;
}

int main() {
     string s = "Hello";
     cout<<CopyString(s,2,5);
}

【问题讨论】:

  • std::string 默认为空。索引运算符[] 不创建任何字符,它只能访问现有字符。
  • 好的,非常感谢!

标签: c++ string


【解决方案1】:

您似乎正在尝试从现有字符串创建子字符串。你总是可以使用substr。它有两个参数,第一个参数指定起始索引,第二个参数指定要复制的字符数。

string s = "Hello";
std::cout << s.substr(2,3) << std::endl;

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2022-11-30
    • 2012-05-09
    相关资源
    最近更新 更多