C语言 从用户输入返回唯一字符数组(唯一字符串)



所以,我的主要任务是返回一个由唯一字符组成的字符数组,但顺序与用户输入中的顺序相同。我已经完成了下面的一个函数,它看起来是可行的,但是当我输入任何东西作为输入时,什么也不返回。

jooooooe应该返回Joe。鲁伯特应该把罗伯特还给他。阿尔伯特应该归还阿尔贝。同样,duccck应该返回Duck。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void unique_string(char* new_string) {

char updated_string[251];
int counter = 0;

for (int i = 0; i < strlen(new_string); ++i) {

char new_char = new_string[i];

char *potential_candidate;
potential_candidate = strchr(updated_string, new_char);
if (potential_candidate != NULL) {
updated_string[counter] = *potential_candidate;
counter++;
printf("%c", *potential_candidate);
}
}
}
int main() {

char new_string[251]; //max of 250 characters
scanf("%s", new_string);

unique_string(new_string);
}

英文字母表中有26个字母。

您可以很容易地创建一个bool值数组,表示字符是否以前见过(初始化为所有false)。

对于输入的每个字符,将其转换为索引,其中'a'0,'b'1,以此类推。然后检查当前字符位置中的"已被看到";数组中。如果是false,打印字符并将其设置为true。否则,跳过打印,继续输入下一个字符。

使用isalpha确保字符是字母,使用tolowertoupper使其与大小写无关。

最新更新