c++ - 在字符串上使用调整大小

标签 c++ string function resize user-defined-functions

大家好,我试图寻找答案,但找不到。 (我找到了如何使用它)但问题是我只是不知道为什么我的代码不起作用。这是我的代码:

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

string acorta(string palabra, int carac)
{   
    string acortado;

    acortado=palabra;
    if(palabra.length() > carac)
    {
        return acortado;
    }
    else
    {
        acortado.resize(carac);
        return acortado;
    }
}

int main(int argc, char** argv) {

    cout<< acorta("Univesidad",5)<<endl; // here it should show "Unive"
    cout<< acorta("Secretariado",10)<<endl; //here it should show "Secretaria"
    cout<< acorta("Estudio",11)<<endl; //here it should show "Estudio" since th number               is long than the word

    return 0;
}

好吧,程序应该接收一个字符串和一个整数,因为它应该按照 int 的要求返回字符串。例如 ("Laptop",4) 它应该返回 "Lapt"。如果 int 大于单词,那么它应该返回整个单词。

问题是程序在不应该做的时候返回了整个单词。所以我认为问题在于它没有进入我的功能。如果我错了,请纠正我。

最佳答案

if(palabra.length() > carac)

如果它比你传入的整数长,你告诉它返回原始字符串。你想反转它:

if(palabra.length() <= carac)

更好的是,不要重复自己,也不需要不必要的参数拷贝,它已经是原始参数的拷贝:

if(palabra.length() > carac)
{
    palabra.resize(carac);
}

return palabra;

或者,您可以使用 substr 函数,但如果您不想做不必要的子字符串,您可以调整它:

return palabra.substr(0, carac);

如果这样做,您甚至不再需要字符串的拷贝:

string acorta(const string &palabra, int carac)

关于c++ - 在字符串上使用调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17160570/

相关文章:

java - 使用简单的扫描仪,读取带空格的字符串,为什么 .trim() 方法不起作用?

c - 如何影响 C 中结构的相同副本?

php - 将变量传递给 wordpress 过滤器中的匿名函数

c++ - 编写管理程序?

c++ - SIGSEGV 声明

c - 不同的 SHA-256 哈希值取决于输入是使用 sizeof 还是 strlen 测量

java - 如何在程序中仅打印斜杠 "/"之前的字母?

c++ - 以编程方式在 Windows 上隐藏应用程序

c++ - 以编程方式处理 Cocoa 事件?

javascript 使用函数的方法创建对象的更好方法