简体   繁体   English

如果有两个相同的字母彼此相邻,则在字符串中添加其他字母

[英]add additional letters in a string if there are two same letters beside each other

I'm trying to add an additional letter if there are two equal letters beside each other.如果彼此旁边有两个相等的字母,我会尝试添加一个额外的字母。 That's what I was thinking, but it doesn't put in an x between the two letters;这就是我的想法,但它没有在两个字母之间放入 x; instead of that, it copies one of the double letters, and now I have, for example, MMM instead of MXM.取而代之的是,它复制了双字母之一,例如,现在我拥有 MMM 而不是 MXM。

for (index_X = 0; new_text[index_X] != '\0'; index_X++)
  {
    if (new_text[index_X] == new_text[index_X - 1])
    {
      double_falg = 1;
    }
    text[index_X] = new_text[index_X];
  }
  
  
  if (double_falg == 1)
  {
    for (counter_X = 0; text[counter_X] != '\0'; counter_X++)
    {
      transfer_X = counter_X;
      if (text[transfer_X - 1] == text[transfer_X])
      {
        text_X[transfer_X] = 'X';
        cnt_double++;
        printf("%c\n", text[transfer_X]);

      }
      text_X[transfer_X] = text[transfer_X - cnt_double];
    }
    printf("%s\n", text_X);
  }

If you're trying to create the modified array in text_X , copying data from new_text and putting an X between adjacent repeated letters (ignoring the possibility that the input contains XX ), then you only need:如果您尝试在text_X创建修改后的数组,从new_text复制数据并将X放在相邻的重复字母之间(忽略输入包含XX的可能性),那么您只需要:

char new_text[] = "data with appalling repeats";
char text_X[SOME_SIZE];
int out_pos = 0;

for (int i = 0; new_text[i] != '\0'; i++)
{
    text_X[out_pos++] = new_text[i];
    if (new_text[i] == new_text[i+1])
        text_X[out_pos++] = 'X';
}
text_X[out_pos] = '\0';

printf("Input:  [%s]\n", new_text);
printf("Output: [%s]\n", text_X);

When wrapped in a basic main() function (and enum { SOME_SIZE = 64 }; ), that produces:当包含在基本的main()函数中(和enum { SOME_SIZE = 64 }; )时,会产生:

Input:  [data with appalling repeats]
Output: [data with apXpalXling repeats]

To deal with repeated X's in the input, you could use:要处理输入中重复的 X,您可以使用:

text_X[out_pos++] = (new_text[i] == 'X') ? 'Q' : 'X';

It seems that your approach is more complicated than needed - too many loops and too many arrays involved.似乎您的方法比需要的更复杂 - 涉及太多循环和太多数组。 A single loop and two arrays should do.一个循环和两个数组应该可以。

The code below iterates the original string with idx to track position and uses the variable char_added to count how many extra chars that has been added to the new array.下面的代码使用idx迭代原始字符串以跟踪位置,并使用变量char_added来计算已添加到新数组中的额外字符数。

#include <stdio.h>

#define MAX_LEN 20

int main(void) {
    char org_arr[MAX_LEN] = "aabbcc";
    char new_arr[MAX_LEN] = {0};
    int char_added = 0;
    int idx = 1;
    new_arr[0] = org_arr[0];
    if (new_arr[0])
    {
        while(org_arr[idx])
        {
            if (org_arr[idx] == org_arr[idx-1])
            {
                new_arr[idx + char_added] = '*';
                ++char_added;
            }
            new_arr[idx + char_added] = org_arr[idx];
            ++idx;
        }
    }
    puts(new_arr);
    return 0;
}

Output:输出:

a*ab*bc*c

Note: The code isn't fully tested.注意:代码未经过全面测试。 Also it lacks out-of-bounds checking.它也缺乏越界检查。

There is a lot left to be desired in your Minimal, Complete, and Verifiable Example (MCVE) (MCVE).在您的最小、完整和可验证示例 (MCVE) (MCVE) 中还有很多需要改进的地方。 However, that said, what you will need to do is fairly straight-forward.但是,话虽如此,您需要做的是相当简单的。 Take a simple example:举个简单的例子:

"ssi"

According to your statement, you need to add a character between the adjacent 's' characters.根据您的说法,您需要在相邻的's'字符之间添加一个字符。 (you can use whatever you like for the separator, but if your input are normal ASCII character, then you can set the current char to the next ASCII character (or subtract one if current is the last ASCII char '~' )) See ASCII Table and Description . (您可以使用任何您喜欢的分隔符,但如果您的输入是正常的 ASCII 字符,那么您可以将当前字符设置为下一个 ASCII 字符(如果当前是最后一个 ASCII 字符'~'则减去一个))参见ASCII表和说明

For example, you could use memmove() to shift all characters beginning with the current character up by one and then set the current character to the replacement.例如,您可以使用memmove()将所有以当前字符开头的字符上移一位,然后将当前字符设置为替换字符。 You also need to track the current length so you don't write beyond your array bounds.您还需要跟踪当前长度,以免写入超出数组范围。

A simple function could be:一个简单的函数可能是:

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

#define MAXC 1024

char *betweenduplicates (char *s)
{
    size_t len = strlen(s);                         /* get length to validate room */
    
    if (!len)                                       /* if empty string, nothing to do */
        return s;
    
    for (int i = 1; s[i] && len + 1 < MAXC; i++)    /* loop until end, or out of room */
        if (s[i-1] == s[i]) {                           /* adjacent chars equal? */
            memmove (s + i + 1, s + i, len - i + 1);    /* move current+ up by one */
            if (s[i-1] != '~')                          /* not last ASCII char */
                s[i] = s[i-1] + 1;                      /* set to next ASCII char */
            else
                s[i] = s[i-1] - 1;                      /* set to previous ASCII char */
            len += 1;                                   /* add one to len */
        }
    
    return s;       /* convenience return so it can be used immediately if needed */
}

A short example program taking the string to check as the first argument could be:将要检查的字符串作为第一个参数的简短示例程序可以是:

int main (int argc, char **argv) {
    
    char str[MAXC];
    
    if (argc > 1)                           /* if argument given */
        strcpy (str, argv[1]);              /* copy to str */
    else
        strcpy (str, "mississippi");        /* otherwise use default */
    
    puts (str);                             /* output original */
    puts (betweenduplicates (str));         /* output result */
}

Example Use/Output示例使用/输出

$ ./bin/betweenduplicated
mississippi
mistsistsipqpi

or when there is nothing to replace:或者当没有什么可以替换时:

$ ./bin/betweenduplicated dog
dog
dog

Or checking the extremes:或检查极端情况:

$ ./bin/betweenduplicated "two  spaces  and  alligators  ~~"
two  spaces  and  alligators  ~~
two ! spaces ! and ! almligators ! ~}~

There are a number of ways to approach it.有多种方法可以接近它。 Let me know if you have further questions.如果您还有其他问题,请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM