gpt4 book ai didi

c++ - 如何在c中查找同一字符串中该字符的第一次重复出现

转载 作者:行者123 更新时间:2023-11-30 20:59:24 26 4
gpt4 key购买 nike

如何让重复字符第一次出现时仅打印该字符。区分大小写或不区分大小写无关紧要。例如对于输入=“opuott”答案=o/O 输入=“kuttu”答案=t/T

#include<stdio.h>
#include<string.h>
int main(){
int i,j,diff=0,min=0;
char arr[100],var;
printf("Enter the string to check for: ");
scanf("%s",&arr);
for(i=0;i<strlen(arr);i++){
arr[i]=toupper(arr[i]);
printf("%c ",arr[i]);
}
printf("\n");
for(i=0;i<strlen(arr);i++){
for(j=i+1;j<strlen(arr);j++){
if(arr[i]==arr[j]){
diff=j-i;
//THIS IF BLOCK IS USED FOR FIRST CONDITION FAILURE OF MIN AND DIFFERENCE
if(diff > min){
min=diff;
var=arr[i];
}
//THIS ELSE BLOCK IS USED FOR REGULAR CHECK FOR THE MIN AND DIFF AND ADJUST MIN TO DIFF ACCORDINGLY
else if(diff < min){
min=diff;
var=arr[i];
}
}
}
}
printf("Final Answer : %c\n",var);
return 0;
}

最佳答案

在 C 中,区分大小写的解决方案可以是这样的:

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

int repeated_char(char arr[],bool char_arr[],size_t len){
int i;
for(i=0;i<len;i++){
if (char_arr[arr[i]] == true)
return arr[i];
else
char_arr[arr[i]] = true;
}
return -1;
}

int main(){

char arr[100];
bool char_arr [256];

printf("Enter the string to check for: ");
scanf("%100s",&arr);
size_t arr_len = strlen(arr);
memset(char_arr,false,sizeof(char_arr));
char ans = repeated_char(arr,char_arr,arr_len);
if (ans == -1)
printf("No repeated chars were found");
else
printf("%c",ans);
}

输入:“nabc-=1nabc”

输出:n

关于c++ - 如何在c中查找同一字符串中该字符的第一次重复出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47654191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com