C++ - 如何将一个字符附加到字符*?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19891962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:14:08  来源:igfitidea点击:

C++ - How to append a char to char*?

c++charappend

提问by sonlexqt

I've tried so may ways on the Internet to append a character to a char* but none of them seems to work. Here is one of my incomplete solution:

我已经尝试过在 Internet 上将字符附加到 char* 的方法,但它们似乎都不起作用。这是我不完整的解决方案之一:

char* appendCharToCharArray(char * array, char a)
{
    char* ret = "";
    if (array!="") 
    {
        char * ret = new char[strlen(array) + 1 + 1]; // + 1 char + 1 for null;
        strcpy(ret,array);
    }
    else
    {
        ret = new char[2];
        strcpy(ret,array);
    }

    ret[strlen(array)] = a;  // (1)
    ret[strlen(array)+1] = '
char* appendCharToCharArray(char* array, char a)
{
    size_t len = strlen(array);

    char* ret = new char[len+2];

    strcpy(ret, array);    
    ret[len] = a;
    ret[len+1] = '
std::string str;

str.append('x');
// or
str += x;
'; return ret; }
'; return ret; }

This only works when the passed array is "" (blank inside). Otherwise it doesn't help (and got an error at (1)). Could you guys please help me with this ? Thanks so much in advanced !

这仅在传递的数组为“”(内部空白)时有效。否则它没有帮助(并且在(1)处出错)。你们能帮我解决这个问题吗?非常感谢先进!

回答by masoud

Remove those char * retdeclarations inside ifblocks which hide outer ret. Therefor you have memory leak and on the other hand un-allocated memory for ret.

删除隐藏外部的块char * ret内的那些声明。因此,您有内存泄漏,另一方面.ifretret

To compare a c-style string you should use strcmp(array,"")not array!="". Your final code should looks like below:

要比较 c 样式的字符串,您应该使用strcmp(array,"")not array!=""。您的最终代码应如下所示:

bool AppendCharToCharArray( char *array, size_t n, char c )
{
    size_t sz = std::strlen( array );

    if ( sz + 1 < n ) 
    {
        array[sz] = c;
        array[sz + 1] = '
char * CharArrayPlusChar( const char *array, char c )
{
    size_t sz = std::strlen( array );
    char *s = new char[sz + 2];

    std::strcpy( s, array );
    s[sz] = c;
    s[sz + 1] = '
char * ret = new char[strlen(array) + 1 + 1];
^^^^^^ Remove this
'; return ( s ); }
'; } return ( sz + 1 < n ); }

Note that, you must handle the allocated memory of returned retsomewhere by delete[]it.

请注意,您必须处理它在ret某处返回的分配内存delete[]

 

 

Why you don't use std::string? it has .appendmethod to append a character at the end of a string:

你为什么不使用std::string?它有.append在字符串末尾附加一个字符的方法:

if (array!="")     // Wrong - compares pointer with address of string literal
if (array[0] == 0) // Better - checks for empty string

回答by Vlad from Moscow

The function name does not reflect the semantic of the function. In fact you do not append a character. You create a new character array that contains the original array plus the given character. So if you indeed need a function that appends a character to a character array I would write it the following way

函数名不反映函数的语义。实际上,您没有附加字符。您创建一个包含原始数组和给定字符的新字符数组。因此,如果您确实需要一个将字符附加到字符数组的函数,我会按以下方式编写它

std::string appendCharToString(std::string const & s, char a) {
    return s + a;
}

If you need a function that will contain a copy of the original array plus the given character then it could look the following way

如果您需要一个包含原始数组副本和给定字符的函数,则它可能如下所示

char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;

回答by Mike Seymour

The specific problem is that you're declaring a new variable instead of assigning to an existing one:

具体问题是您要声明一个新变量而不是分配给现有变量:

test

and trying to compare string values by comparing pointers:

并尝试通过比较指针来比较字符串值:

##代码##

although there's no need to make that comparison at all; the first branch will do the right thing whether or not the string is empty.

尽管根本没有必要进行这种比较;无论字符串是否为空,第一个分支都会做正确的事情。

The more general problem is that you're messing around with nasty, error-prone C-style string manipulation in C++. Use std::stringand it will manage all the memory allocation for you:

更普遍的问题是你在 C++ 中处理讨厌的、容易出错的 C 风格的字符串操作。使用std::string它将为您管理所有内存分配:

##代码##

回答by Safa Seed

##代码##

OUTPUT:

输出:

##代码##