如何从字符指针One复制到Anothe Char Pointer,并在之间添加字符

发布于 2025-01-31 04:22:47 字数 1105 浏览 2 评论 0原文

我想在c中写下带有句子的char指针的功能,在每个地方都有逗号','我想添加空间' 我写了此功能

char* add_space_after_comma(char* textArr){
char* newText=(char *)malloc(strlen(textArr) * sizeof(textArr));
char* temp = newText;
int i;    
int indexNew=0;
int maxSize = strlen(textArr)-1;
if(newText  == NULL) 
    {
        printf("memory allocation failed \n");
        exit(0);    
    }
for (i = 0; textArr[i] != '\0'; i++, indexNew++) {
        if(indexNew == maxSize-1){
        
                temp = (char*)realloc(newText, maxSize*ARR_SIZE*sizeof(char));

                if(temp == NULL)
                {
                    printf("memory allocation failed \n");
                    exit(0);
                }
            maxSize= maxSize * ARR_SIZE;
            newText =temp;
        }
        newText[indexNew] = textArr[i];
        if(textArr[i] == ','){
        indexNew++;
        newText[indexNew] = ' ';
        }
    }
indexNew++;
newText[indexNew] = '\0';

printf("\nthe new text is: %s\n", newText);
return (char*)newText;
}

,但是当我试图运行和检查它时,将其打印到屏幕

新文本是: v。

-

i want to write function in c that gets char pointer with sentence inside, and in every place there is comma ',' i want to add space ' ' after the comma
i write this function

char* add_space_after_comma(char* textArr){
char* newText=(char *)malloc(strlen(textArr) * sizeof(textArr));
char* temp = newText;
int i;    
int indexNew=0;
int maxSize = strlen(textArr)-1;
if(newText  == NULL) 
    {
        printf("memory allocation failed \n");
        exit(0);    
    }
for (i = 0; textArr[i] != '\0'; i++, indexNew++) {
        if(indexNew == maxSize-1){
        
                temp = (char*)realloc(newText, maxSize*ARR_SIZE*sizeof(char));

                if(temp == NULL)
                {
                    printf("memory allocation failed \n");
                    exit(0);
                }
            maxSize= maxSize * ARR_SIZE;
            newText =temp;
        }
        newText[indexNew] = textArr[i];
        if(textArr[i] == ','){
        indexNew++;
        newText[indexNew] = ' ';
        }
    }
indexNew++;
newText[indexNew] = '\0';

printf("\nthe new text is: %s\n", newText);
return (char*)newText;
}

but when im trying to run and check it, its print to the screen

the new text is: �����T$
�v���넍�&

how can i write this function rigth?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夏有森光若流苏 2025-02-07 04:22:47

对于初学者,应使用限制符cosnt声明函数参数,因为传递的字符串在函数中没有更改。该函数根据源字符串的内容创建一个新字符串。

char * add_space_after_comma( const char* textArr );

此声明中的内存分配

char* newText=(char *)malloc(strlen(textArr) * sizeof(textArr));

等同于

char* newText=(char *)malloc(strlen(textArr) * sizeof( char * ));

,显然没有意义。

内存重新分配效率

temp = (char*)realloc(newText, maxSize*ARR_SIZE*sizeof(char));

低下,也没有意义。首先,您需要计算逗号的发生,然后立即分配具有所需尺寸的数组。

for循环后的索引的这种增加

indexNew++;

是错误的。您需要删除此语句。

而且您需要确保通过的指针确实指向字符串。

该函数可以被声明和定义,如下面的演示程序所示。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * add_space_after_comma( const char* textArr )
{
    const char c = ',';

    size_t count = 0;

    for ( const char *p = textArr; ( p = strchr( p, c ) ) != NULL; ++p )
    {
        ++count;
    }

    char *result = malloc( strlen( textArr ) + 1 + count );

    if ( result != NULL )
    {
        char *t = result;
        for ( const char *p; ( p = strchr( textArr, c ) ) != NULL; textArr = p + 1 )
        {
            size_t n = p - textArr + 1;
            memcpy( t, textArr, n );
            t[n++] = ' ';
            t +=n;
        }

        strcpy( t, textArr );
    }

    return result;
}

int main ()
{
    const char *textArr = "1,2,3,4,5";

    printf( "\"%s\"\n", textArr );

    char *result = add_space_after_comma( textArr );

    if ( result != NULL )
    {
        printf( "\"%s\"\n", result );
    }

    free( result );
}    

程序输出是

"1,2,3,4,5"
"1, 2, 3, 4, 5"

For starters the function parameter should be declared with the qualifier cosnt because the passed string is not changed within the function. The function creates a new string based on the content of the source string.

char * add_space_after_comma( const char* textArr );

The memory allocation in this declaration

char* newText=(char *)malloc(strlen(textArr) * sizeof(textArr));

is equivalent to

char* newText=(char *)malloc(strlen(textArr) * sizeof( char * ));

and evidently does not make a sense.

The memory reallocation

temp = (char*)realloc(newText, maxSize*ARR_SIZE*sizeof(char));

is inefficient and also does not make a sense. You need at first to count occurrences of the comma and then at once to allocate an array with the required size.

This incrementing of the index after the for loop

indexNew++;

is wrong. You need to remove this statement.

And you need to be sure that the passed pointer is indeed points to a string.

The function can be declared and defined as shown in the demonstration program below.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * add_space_after_comma( const char* textArr )
{
    const char c = ',';

    size_t count = 0;

    for ( const char *p = textArr; ( p = strchr( p, c ) ) != NULL; ++p )
    {
        ++count;
    }

    char *result = malloc( strlen( textArr ) + 1 + count );

    if ( result != NULL )
    {
        char *t = result;
        for ( const char *p; ( p = strchr( textArr, c ) ) != NULL; textArr = p + 1 )
        {
            size_t n = p - textArr + 1;
            memcpy( t, textArr, n );
            t[n++] = ' ';
            t +=n;
        }

        strcpy( t, textArr );
    }

    return result;
}

int main ()
{
    const char *textArr = "1,2,3,4,5";

    printf( "\"%s\"\n", textArr );

    char *result = add_space_after_comma( textArr );

    if ( result != NULL )
    {
        printf( "\"%s\"\n", result );
    }

    free( result );
}    

The program output is

"1,2,3,4,5"
"1, 2, 3, 4, 5"
冰葑 2025-02-07 04:22:47
  • 就像在注释中指出的那样,如果您一次在输入字符串中计算目标字符,则需要一个malloc()为结果。与一系列realloc() s相比,字符串的一次解析是有效的。
char* suffixChar_forEach (const char* src, const int slen, const char target, const char suffix) {

    int tgt_count = 0;
    for (int ci = 0; ci < slen; ++ci)
        if (target == src[ci])
            ++tgt_count;

    char* nText = malloc (slen + tgt_count + 1);
    if (!nText) {
        perror ("suffixChar_forEach-malloc"); return NULL;
    }
    int nlen = 0;
    for (int ci = 0; ci < slen; ++ci) {
        nText[nlen++] = src[ci];
        if (target == src[ci])
            nText[nlen++] = suffix;
        }
    nText[nlen] = '\0';

    printf ("\nNew text is: [%s]\n", nText);
    return nText;
}
  • 您还可以,在任何给定的target字符之后,将函数通用到后缀 char。
  • 如果需要,您可能还需要从功能中获取strlen(ntext)
  • 相同的功能可用于后缀任何char说'-'(连字符),而不是仅仅''(space):
int main () {
    char str[] = ",.,.,.,.,.,.,.,.,.,;kl;klkl.,.,.,.,.,.";
    printf ("\nInput: [%s]\n", str);

    char* result = suffixChar_forEach(str, strlen(str), ',', '-');
    if (!result) {
        printf ("ERROR: processing string\n");
        return 1;
    }
    printf ("\nResult: [%s]\n", result);
    free (result);
    return 0;
}
  • Like pointed out in the comments, if you count the target-character in input string once, all you need is one malloc() for the result. One time parsing of string is efficient than a series of realloc()s.
char* suffixChar_forEach (const char* src, const int slen, const char target, const char suffix) {

    int tgt_count = 0;
    for (int ci = 0; ci < slen; ++ci)
        if (target == src[ci])
            ++tgt_count;

    char* nText = malloc (slen + tgt_count + 1);
    if (!nText) {
        perror ("suffixChar_forEach-malloc"); return NULL;
    }
    int nlen = 0;
    for (int ci = 0; ci < slen; ++ci) {
        nText[nlen++] = src[ci];
        if (target == src[ci])
            nText[nlen++] = suffix;
        }
    nText[nlen] = '\0';

    printf ("\nNew text is: [%s]\n", nText);
    return nText;
}
  • You can also, make the function generic to suffix a char after any given target character.
  • You may also want to get the strlen(nText) from function if necessary.
  • Same function can be used to suffix any char say '-'(hyphen) instead of just '' (space) :
int main () {
    char str[] = ",.,.,.,.,.,.,.,.,.,;kl;klkl.,.,.,.,.,.";
    printf ("\nInput: [%s]\n", str);

    char* result = suffixChar_forEach(str, strlen(str), ',', '-');
    if (!result) {
        printf ("ERROR: processing string\n");
        return 1;
    }
    printf ("\nResult: [%s]\n", result);
    free (result);
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文