-3

我正在尝试生成一个将字符连接到给定字符串的字符串。

例如,我的字符串是“hello”,字符是“#”。我想生成一个字符串,显示这些的所有可能组合。即,结果可以是“hello#”、“he#llo”、“hell#o”等。

你能提供使用 C 生成这样一个字符串的代码吗?

谢谢你的努力。

4

3 回答 3

1

你需要一些关于算法的帮助。

假设字符串由指针s ,指向char *s = "hello";

要确定随机位置,可以使用rand()stdlib中的。在 C 中,数组(字符串是字符数组,或由 char 指针指向(并以 0 字节结尾)。在每种情况下,arr[0]ptr[0]都是第一个字符)第一个索引为 0。因此最后一个字符位于 [length-1] 处。为确保随机位置在 0 和 length-1 之间,您可以使用模%运算符,例如int position = rand() % strlen(s);,但由于随机字符可能位于末尾,因此您需要将 1 添加到strlen(s)

  • 如上确定位置
  • 创建一个长度为 length(s)+2 的 char 数组(添加随机字符和结尾 0),命名为t
  • s将部分从 0复制到position-1(注意position == 0大小写)到t(例如strncpy
  • concat 到t随机字符(比如t是 1 个字符的字符串,这会更容易,而有一个技巧可以轻松复制一个字符......)(例如strcat
  • 位置连接到s其余部分(注意大小写) position == length(s)
    • 显示
  • 重复恶心

不知道这是一个任务还是你想自己做的事情——不关我的事。但只要尝试一下 - 自己。你会看到的。起初,它是一个 PITA。然后它很有趣!

于 2013-01-10T08:24:33.340 回答
0

在对您的算法外观有所了解之后。

char *base_string = "hello";

string  = calloc(1,sizeof(char)); 

repeat loop (from i = 0 to length of base_string) { 

    string = realloc(old size of string + sizeof(base_string) +2) // +2 : 1 for null terminate string and 1 for #

    new_insert_position_in_string = string + i * (sizeof(base_string) +1);

    reapeat loop (from j = 0 to j< (length of  base_string )) {
        if (j==i) then {
            new_insert_position_in_string[j] = '#';
            new_insert_position_in_string++;
            continue;
        }
        new_insert_position_in_string[j] = base_string[j];
    }
    new_insert_position_in_string[length of  base_string + 1] = '#';

} 

现在由你来推断 C 代码

于 2013-01-10T08:34:26.323 回答
0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void print_combinations(char *some_string,char some_char)
{
   char *new_string = malloc(strlen(some_string) + 2);
   for (unsigned long j = 0; j < (strlen(some_string) + 1); j++)
   {
      unsigned long i = 0;
      unsigned long k = 0;
      for (; i < (strlen(some_string) + 1); i++)
      {
         if (i == j)
         {
            new_string[i] = some_char;
         }
         else
         {
            new_string[i] = some_string[k];
            k++;
         }
      }
      new_string[i] = '\0';
      printf("pattern %lu: %s\n",j+1,new_string); 
   } 
   free(new_string);
}


int main(void)
{
   print_combinations("hello",'#');
}

输出:

pattern 1: #hello    
pattern 2: h#ello    
pattern 3: he#llo    
pattern 4: hel#lo    
pattern 5: hell#o         
pattern 6: hello#
于 2013-01-10T08:24:35.057 回答