用C中的一个替换字符串中的几个字符

问题描述 投票:0回答:1

我需要用一个字符替换几个字符(取决于它们的计数是偶数还是奇数)。如果是偶数,我应该用P替换+,如果与p奇数。

输入:kjlz ++ zux +++

 while(p[i])
{
    j=i;
    k=i;
    length=strlen(p);

    if(p[i]=='*')
    {
        position=i;
    }
    printf("Position is: %d", position);

        while(p[j]=='*')
        {

            counter++;
            j++;


        }

输出:kjlzPzuxp

不确定如何删除几个我知道如何输入的字符。

c string
1个回答
0
投票

您无需删除/插入字符-更好地“就地”替换它们。似乎也不需要变量position,可以改用i

while(p[i])
{
    if(p[i]=='*')
    {
        printf("Position is: %d", i);

        if (position % 2 == 0) // even or odd?
            p[i] = 'P'; // even
        else
            p[i] = 'p'; // odd
    }

    i++;
}

当然,您可以将if...else...替换为:

p[i] = (i % 2 == 0) ? 'P' : 'p';

或:

p[i] = (i % 2) ? 'p' : 'P';

或不取模(内部使用除法:]

p[i] = (i & 0x1) ? 'p' : 'P';

0
投票

嗯,我建议您创建一个new变量来存储输出。它可能不是最节省内存的方法,但它可以工作。首先,您要计算原始文本的长度,并创建一个相同长度的新char数组。然后,您开始将每个值从原始文本复制到输出变量,直到找到“ +”。在这种情况下,您开始计算有多少个连续的加号。一旦知道这一点,就可以决定是否应添加字母P或p。保留一个单独的索引以写入您的输出!

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


int main (void)
{
    char text[] = "kjlz++zux+++";
    int len = sizeof(text) / sizeof(text[0]);
    char output[len];
    int index = 0, count = 0;

    for(int i = 0; i < len; i++)
    {
        if(text[i] == '+')
        {
            count = 0;
            while(text[i] == '+') i++, count++;
            printf("%d\n", count);
            if(count == 2)
            {
                output[index] = 'P';
            }
            else
            {
                output[index] = 'p';
            }
        }
        else
        {
            output[index] = text[i];
        }
        index++;
    }
    output[index] = 0;
    printf(output);
}
© www.soinside.com 2019 - 2024. All rights reserved.