I keep getting this error when trying to cut out all repeating characters:
solution.c:16:26: error: expression is not assignable
(int)strlen(str1)--;
~~~~~~~~~~~~^
I am trying to do a program to check if a given string of scrambled characters could be rearranged into a given word. Link to Codewars Kata: https://www.codewars.com/kata/55c04b4cc56a697bb0000048/train/c.
My full code:
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
bool scramble(char *str1, char *str2)
{
/* solution here */
bool indicator = false;
for(int i=0; i<(int)strlen(str1); i ){
char ch = str1[i];
for(int j=i 1; j<(int)strlen(str1); ){
if(str1[i] == str1[j]){
for(int k=j; k<(int)strlen(str1); k ){
str1[k] = str1[k 1];
}
(int)strlen(str1)--;
} else {
j ;
}
}
}
for (int i = 0; i < (int)strlen(str2); i ) {
for (int j = 0; j < (int)strlen(str1); j ) {
if (str1[j] == str2[i]) {
indicator = true;
}
}
if (indicator == true) {
continue;
} else {
return false;
}
}
//printf("%d\n", indicator);
if (indicator == true) {
return true;
} else {
return false;
}
}
In order for me to complete this problem I have to shorten the string and remove all repeating characters from the scrambled string. How can I solve this issue, or if I can't at all, then how can I shorten the string after a char removal?
CodePudding user response:
If you want to remove the last character:
if(*str)
{
str[strlen(str) - 1] = 0;
}
if
is needed to handle strings having 0
length, which cannot be shortened
str[strlen(str) - !!*str] = 0;
CodePudding user response:
I must admit, I didn't analyze your code :-)
However, you are working on so-called "C-strings", which are just sequences of characters with a terminating 0 after the last character of the string (that's a binary 0, not the character "0").
These strings are not "objects" of any kind; "strlen", in particular, is not a property or something like that -- it's a function that just counts the characters until it hits the 0.
(int)strlen(str1)--;
basically attempts to reduce a non-existent variable by one -- so that can't work. Besides, as I've just explained, adding or subtracting anything from the result of strlen() doesn't do anything. It's just a computed number.
Instead, when you change the string data, you have to make sure that the terminating 0 ends up in the correct place -- that's the "end of string" marker. Since strlen() is just counting up until it hits that 0, it will always return the correct length.
Depending on where the strings come from, you might not be able to change them at all; you will have to take appropiate precautions so these strings are writable, and if you're making them longer than before, you must allocate enough memory for them.
If that sounds like a lot detail-work -- that's correct. In 2022, we now have C and the "std::string" class, which usually makes things easier...