c - 函数 invertNumerSubstrings 不起作用

标签 c string char ansi-c

我在 Ansi C 中遇到这个问题

3 创建一个函数,该函数接收每次解码的 20 个字符的字符串数组,请考虑以下因素: A。从左到右阅读,数字表示从那里开始要投入多少个字符(要投入的字符之间可以是数字,为此, 被视为常见字符)。
b.数字字符应替换为字符串的第一个字符反转。

示例。字符串 aj5pr2*dfkl3abc2qwe1azk 必须是 ajd*2rpfklcbawqeazk

使用符号和指针算术

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

#define TAM 20


char* invertNumerSubstrings(char*);

int main()
{
    char chain[TAM];
    printf("\n Ingrese chain: ");
    gets(chain);
    fflush(stdin);
    char result;
    result=invertNumerSubstrings(chain);
    printf("\n Chain modified: ");
    puts(chain);
    printf("\n");   
    return 0;
}

char* invertNumerSubstrings(char* chain)
{
    int flag =0;
    char *pl= chain;
    char *pe= chain;
    char aux;
    while(*pl=='\0'&& *pe=='\0');
    {
        if(!(*pl=='1')&&(*pe=='9'))
        {
            pl++;
            pe++;
        }
        else
        {

            if(flag ==0)
            {
                pe=*pl;
                flag=1;
                pl--;
            }
            if(*pe<*pl)
            {
                aux=*pl;
                *pl=*pe;
                *pe=aux;
            }
        }
    }
    return *chain;
}

该程序没有编译错误,但无法运行

最佳答案

您的代码中存在许多问题。指点其中一些。在函数 main()

char result;
result=invertNumerSubstrings(chain);

函数invertNumerSubstrings的返回类型是char*,与结果的类型不匹配。

while(*pl=='\0'&& *pe=='\0');
上述语句中的

; 在逻辑上是不正确的,如果条件满足,可能会导致无限执行循环。 *pl=='\0'&& *pe=='\0' 根据问题的需要,条件看起来并不完美(如果我错了,请纠正我)。

return *chain; 

return 语句是函数 invertNumerSubstrings 的最后一条语句,其返回类型与 char* 不匹配。

要获得所需的输出,您可以尝试以下操作:

void invertNumerSubstrings(char* chain)
{

char *pl= chain;
char* chain_ptr=chain;   // chain_ptr to hold starting address of chain
char* final=(char*)malloc(sizeof(chain));
char* final_ptr=final;  // // final_ptr to hold starting address of final
memset(final, '\0', sizeof(chain));

while(*pl!='\0')
{

    if(*pl>=49 && *pl<=57) //
    {   
         int shift=*pl-48; // to find the shift amount
         int i=0;
         *pl++;

         for(i=shift-1; i>=0; i--){
             *final=*(pl+i);
             final++;
         }
       pl=pl+shift;  // seek the pointer to correct position            
    }

     else
         {
              *final=*pl;
               pl++;
               final++;

         }
}

chain=chain_ptr; // assign original address of chain to chain again

while(*final_ptr !='\0'){
      *chain=*final_ptr ;
      final_ptr++;
      chain++;             
}
*chain='\0';

free(final);

}

假设:当字符串中遇到整数时,则其后续字符串的长度至少等于整数值。

关于c - 函数 invertNumerSubstrings 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26554300/

相关文章:

c++ - Arduino阵列内存使用

c - 在 C 中重新初始化 const char 数组不会给出错误

java - Log4j 最大字符串长度或 Java 字符串连接错误?

c - scanf 一次获取多个值

c++ - 如何在 Arduino serial read() 上将 char 转换为 int?

c - 双向链表: Deleting all occurrences of a given key

c - C语言程序开头的 "main()"是什么意思?

c++ - 我如何将 QString 转换为 char*

c - 函数 ‘strtok_r’ 的隐式声明尽管包含 <string.h>

c - 结构数组初始化