我希望它会对你有所帮助,它是一个有效的代码。我只是对您的程序进行了非常小的更改并添加了所需的内容。很快我会优化这个。但首先要通过下面的代码来理解这个概念。
#include<stdio.h>
int isCharExist(char *str, char c){
int i=0;
while(str[i] != NULL){
if(str[i] == c){
return 1;
}
i++;
}
return 0;
}
char *common(char *a, char *b){
char *result = "";
int index = 0,i,j;
for (i = 0; i < strlen(a); i++){
for ( j = 0; j < strlen(b); j++){
if (a[i] == b[j]){
if(!isCharExist(result, a[i])){
result[index++] = a[i];
result[index] = '\0';//last character of string is always NULL
}
}
}
}
return result;
}
void main(){
char *result = "",*str1,*str2;
//better to assign space before assignment
str1 = "hello world";
str2 = "thank you";
//clrscr();
result = common(str1,str2);
printf("%s",result);
}
下面的代码比上面的代码要好,并且有一些小的改动,为了您更好地理解,我没有删除它。
#include<stdio.h>
int isCharExist(char *result, char c);
char *common(char *a, char *b);
int isCharExist(char *result, char c){
//this function help you to find that current character
//is in your result or not
int i=0;
while(result[i] != NULL){
if(result[i] == c){
//if it find character in result string it return 1
return 1;
}
i++;
}
return 0;//if not find then it return 0
}
char *common(char *a, char *b){
char *result = "";
int index = 0,i,j;
//it is good to keep length in seprate variable before loop
//in loop it calculate length each time
int len1 = strlen(a);
int len2 = strlen(b);
for (i = 0; i < len1; i++){
for ( j = 0; j < len2; j++){
//check equality but not for blank
if (a[i] == b[j] && a[i] != ' '){
if(!isCharExist(result, a[i]))
{
result[index++] = a[i];
result[index] = '\0';//last character of string is always NULL
}
}
}
}
return result;
}
void main(){
char *result = "",*str1,*str2;
//better to assign space before assignment
str1 = "hello world";
str2 = "thank you";
//clrscr();
result = common(str1,str2);
printf("%s",result);
}
以上只是你函数的一些改动,所以只是替换你的函数不是完整的代码。
char *common(char *a, char *b){
char *result = "";
int index = 0,i,j,k, isDuplicate=0;
//it is good to keep length in seprate variable before loop
//in loop it calculate length each time
int len1 = strlen(a);
int len2 = strlen(b);
for (i = 0; i < len1; i++){
for ( j = 0; j < len2; j++){
//check equality but not for blank
if (a[i] == b[j] && a[i] != ' '){
k = 0;
while(result[k] != '\0'){
if(a[i] == result[k]){
isDuplicate = 1;
break;
}
k++;
}
if(!isDuplicate)
{
result[index++] = a[i];
result[index] = '\0';//last character of string is always NULL
}
isDuplicate = 0;
}
}
}
return result;
}