2013-01-10 47 views
-3

我想要生成一個字符串連接到一個給定的字符串的字符。如何將一個字符隨機附加到一個字符串?

例如,我的字符串是「你好」,字符是「#」。我想生成一個顯示所有可能的組合的字符串。即結果可以是「hello#」,「he#llo」,「hell#o」等。

你能提供用C語言生成這樣一個字符串的代碼嗎?

謝謝你的努力。

+2

有你開始嘗試打破這個問題?列出時,您會注意到所有可能的組合模式? – chris

+0

@ArunG:你會如何編寫這段代碼?你有什麼嘗試? – kerim

+2

你應該首先展示你自己的努力,這就是這個網站的工作原理。 –

回答

1

您需要一些關於算法的幫助。

假定字符串被指針指向schar *s = "hello";

要確定隨機位置,您可以使用stdlib庫中的rand()。在C語言中,數組(字符串是字符數組,或者由char指針指向(以0字節結尾)。在任何情況下,arr [0]ptr [0]是第一個char)的第一個索引是0.因此最後一個字符在[length-1]。爲了確保隨機位置在0和長度-1之間,可以使用模%運算符,例如int position = rand() % strlen(s);,但由於隨機字符可能在末尾,因此您需要將1加到strlen(s)

  • 確定位置如上
  • 創建長度的字符數組是長度(S)2(隨機炭&結束0被添加)命名
  • 從0複製s部分position-1(提防position == 0案件)插入(例如函數strncpy
  • 的concat到隨機查R(比如說是1個字符的字符串,那會是更加容易,同時還有一招復制容易只是一個字符...)(例如strcat的
  • CONCAT到剩餘從位置小號即部分(小心position == length(s)案件)
    • 顯示
  • 重複廣告Naus談eum

不知道這是一項任務還是你自己想做的事 - 我的業務無關。但只是試一試 - 由你自己。你會看到的。起初,它是一個PITA。然後它很有趣!

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# 
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代碼

相關問題