我想要生成一个字符串连接到一个给定的字符串的字符。如何将一个字符随机附加到一个字符串?
例如,我的字符串是“你好”,字符是“#”。我想生成一个显示所有可能的组合的字符串。即结果可以是“hello#”,“he#llo”,“hell#o”等。
你能提供用C语言生成这样一个字符串的代码吗?
谢谢你的努力。
我想要生成一个字符串连接到一个给定的字符串的字符。如何将一个字符随机附加到一个字符串?
例如,我的字符串是“你好”,字符是“#”。我想生成一个显示所有可能的组合的字符串。即结果可以是“hello#”,“he#llo”,“hell#o”等。
你能提供用C语言生成这样一个字符串的代码吗?
谢谢你的努力。
您需要一些关于算法的帮助。
假定字符串被指针指向s,char *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
部分position-1
(提防position == 0
案件)插入吨(例如函数strncpy)position == length(s)
案件)
不知道这是一项任务还是你自己想做的事 - 我的业务无关。但只是试一试 - 由你自己。你会看到的。起初,它是一个PITA。然后它很有趣!
#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#
这里你的算法看起来如何的想法后。
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代码
有你开始尝试打破这个问题?列出时,您会注意到所有可能的组合模式? – chris
@ArunG:你会如何编写这段代码?你有什么尝试? – kerim
你应该首先展示你自己的努力,这就是这个网站的工作原理。 –