EDIT: I think I've understood how this concept works, this is my code
void delete_duplicate(char* str) {
if (str == NULL) {
exit(1);
}
for (size_t i = 0; str[i] != 0; i ) {
if (str[i] == str[i 1]) {
str[i] = '\0';
}
}
}
int main(void) {
char str[] = "hhhhhhhheeeeeeeeyyyyyyyyyyy";
delete_duplicate(str);
return 0;
}
the output string is "00...0h0...000e0...000y" (with lots of zeros). if the string is "abbbb", the string becomes "a" and not "ab".
I was thinking about an algorithm for this exercise:
given a string, for example "ssttringg" the output must be "string". the function has to remove one character if and only if the current character and the next character are the same.
the exercise expects a function declared like this:
extern void delete_consecutive(char* str);
this is my algorithm:
- loop: if the current character is equal to the next character, increment length by 1, and repeat until zero terminator is reached.
critical part: dynamic memory allocation.
- allocate enough memory to store the output. Why did I say this is the critical part? because I have to do it in a void function, therefore I can't create a second string, allocate enough memory with malloc, and then return it at the end. I need to edit the original string instead. I think I can do it by means of a realloc, and by decrementing the size of the string. But I don't know how to do it, and more important: I don't know if it's legit to do it, without losing data. I think I'm overcomplicating the homework, but it's a void function, therefore I can't simply create a new string and copying characters in it, because I can't return it.
if it's not clear, I'll edit the question.
CodePudding user response:
This isn't an answer, but consider this code:
char str[] = "strunqg";
printf("before: %s\n", str);
modifystring(str);
printf("after: %s\n", str);
where the "modifystring
" function looks like this:
void modifystring(char *p)
{
p[3] = 'i';
p[5] = p[6];
p[6] = '\0';
}
This is totally "legit". It would not work, however, to call
char *str = "strunqg";
modifystring(str); /* WRONG */
or
modifystring("strunqg"); /* WRONG */
Either of these second two would attempt to modify a string literal, and that's not copacetic.
CodePudding user response:
You can modify the string passed as a parameter if it is modifiable.
Example:
void deleteFirstChar(char *str)
{
if(str && *str)
{
memmove(str, str 1, strlen(str));
}
}
//illegal call
//string literals cannot be changed
void foo(void)
{
char *str = "Hello";
deleteFirstChar(str);
}
//legal call
void bar(void)
{
char str[] = "Hello";
deleteFirstChar(str);
}