I am trying to create a function to identify whether or not a character is repeated in a given string.
int checkrow(char* row) {
int count, r;
for(int i = 0; i < strlen(row); i ) {
count = 1;
for(int j = i 1; j < strlen(row); j ) {
if(row[i] == row[j]) {
count = count 1;
}
}
if(count > 1 ) {
r = 0;
}
else {
r = 1;
}
}
return r;
}
This is my function at the moment, I am not getting an error or warning messages, but it is not identifying repeated characters.
I am very new to C and any help would be appreciated!
CodePudding user response:
For each character you test, you set r
to whether that character is repeated. So if the first character is repeated you set r = 0
, but then if the second character is not repeated, you set r = 1
.
You don't need to test every character. As soon you find a repeated character, you can return 0
. If you get to the end of the loop, nothing was repeated, so you return 1
.
int checkrow(char* row) {
for(size_t i = 0; i < strlen(row); i ) {
for(size_t j = i 1; j < strlen(row); j ) {
if(row[i] == row[j]) {
return 0;
}
}
}
return 1;
}