Jump to content
razvandragos29

Remove string function (c)

Recommended Posts

Salut incerc sa fac o functie care are 3 parametri textul sursa , indexul de unde sa se faca stergerea si cate caractere sa fie sterse.

Aceasta e implementarea mea

 
#include <stdio.h>


void removeString(char text[], int startingIndex, int numberToRemove)
{

int lenghtText = 0, i, j;
while(text[lenghtText])
lenghtText++;

if ( startingIndex + numberToRemove < lenghtText)
{
for ( i = startingIndex -1, j = (startingIndex - 1 ) + (numberToRemove - 1); j < lenghtText; i++,j++)
text[i] = text[j]
}

printf("%s ", text);
}


int main (void)
{
void removeString( char text[], int startingIndex, int numberToRemove);

removeString("the wrong son", 4, 6);

return 0;

}

atunci cand incerc sa fac atribuirea primesc segmentation fault din cate am citit pe net nu am acces la aceea zona de memorie insa nu inteleg de ce , text[2] = ar trebui sa insemne al 3 element din acel vector nu ? in cazul textului de mai sus este reprezentat prin spatiu . De ce nu ii pot schimba valoarea ?

Edit:Am rezolvat !

Edited by razvandragos29
Link to comment
Share on other sites

Care e rezolvare ca ma ucide curiozitatea?

Am incercat in in alte moduri si tot segmentation fault imi da. Multumesc :)

Edit: Daca declari o variabila de tip char in main si ii dai ca valoare sirul ala. Iar apoi apelezi functia ca : removeString(variabila, 4, 6); merge. Totusi sunt interesat si de rezolvarea pe care ai gasit-o tu :)

Edited by kznamst
Link to comment
Share on other sites

 #include <stdio.h> 


void removeString(char text[], int startingIndex, int numberToRemove)
{
// char c;
int lenghtText = 0, i, j;
while(text[lenghtText])
lenghtText++;

for ( i = startingIndex, j = startingIndex + numberToRemove ; j <= lenghtText; i++,j++ )
{
if ( text[j] == '\0')
text[i] = '\0';
else
text[i] = text[j];

}





}


int main (void)
{
void removeString( char text[], int startingIndex, int numberToRemove);

char text[] = "the wrong son";

removeString(text, 4, 6);

printf("%s\n", text);

return 0;

}

aceasta este rezolvarea am scos -1 nu calculasem bine conditiile din for + am facut un vector de tip char care sa contina textul pe care vreau sa il reduc .. @Erase in cazul asta eu am initializat variabila text[] , daca mai ai vreo completare sau sfaturi le astept :D

Link to comment
Share on other sites

kznamst, daca declari o variabila in main o si initializezi.In cazul de fata va da eroare pentru ca sirul nu e initializat si se incearca scrierea acestuia.

Salut, "Daca declari o variabila de tip char in main si ii dai ca valoare sirul ala" te rog sa recitesti asta. Mai exact "si ii dai ca valoare sirul ala"=initializezi.

@razvandragos29

eu am scos for-ul ala cu tot si tot imi da segmentation fault


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

void removeString(char text[100], int startingIndex, int numberToRemove)
{
strcpy(text+startingIndex, text+ startingIndex + numberToRemove);
printf("%s ", text);
}


int main (void)
{

removeString('the wrong son', 4, 6);

return 0;

}


Edit: Acum vazusem char-ul :) Gata

Edited by kznamst
Link to comment
Share on other sites

Nu dau doi parametri de tip int, ci dau pozitia unde vreau sa se inceapa copierea si pozitia de unde copiiez.Incearca codul de mai jos :) Returneaza acelasi rezultat ca si al tau.



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

void removeString(char text[100], int startingIndex, int numberToRemove)
{
strcpy(text+startingIndex, text+ startingIndex + numberToRemove);
printf("%s ", text);
}


int main (void)
{
char s[100]="the wrong son";
removeString(s, 4, 6);

return 0;

}

Link to comment
Share on other sites

razvandragos, in primul exemplu nu initializezi sirul si de asta ti-a dat eroare, codul este corect.

int main (void)

{

void removeString( char text[], int startingIndex, int numberToRemove);

//removeString("the wrong son", 4, 6);

char[] str = "the wrong son";

removeString(str, 4, 6);

return 0;

}

kznamst, daca ma inveti pe mine ce inseamna initializarea unei variabile banuiesc ca ar trebui sa stii ca nu poti scrie la o adresa a unei variabile neinitializate.

LE: @razvandragos29, nu de tine era vorba.

Edited by Erase
Link to comment
Share on other sites

@Erase da nu am zis ca te invat eu vreo ceva creca ai inteles gresit ..in linia urmatoare

 char text[] = "the wrong son";

nu am initializat vectorul text ? in primul exemplu nu am initializat textu si dupa am observat si eu aceasta greseala . Daca nu asa e initializarea imi poti explica tu ce si cum nu sunt in concurs cu nimeni vreau doar sa invat

Link to comment
Share on other sites

  • Active Members

Toti v? jucati cu stringuri dar nu vad pe nimeni care s? aloce dinamic (as you should).

Sunt solutii bune pe-aici, dar nu ideale.

E doar un sfat, tratati-l ca atare :-)

// maine revin cu un exemplu, acum sunt pe telefon. Pân? atunci caut? malloc() si încearc? s? implementezi singur.

Edited by MrGrj
Link to comment
Share on other sites

@MrGrj poti transforma codul de mai sus alocand dinamic? Sa imi fac o idee, daca nu e deranjul prea mare. Multumesc

M-am jucat cu malloc(), dar nu stiu cum sa-i atribui sirul ala in program, fara a-l citi cu gets();


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

void removeString(char text[100], int startingIndex, int numberToRemove)
{
strcpy(text+startingIndex, text+ startingIndex + numberToRemove);
printf("%s ", text);
}


int main (void)
{
char *s=malloc(30);

gets(s);
removeString(s, 4, 6);
free(s);
return 0;

}


Edited by kznamst
Link to comment
Share on other sites

Problema este ca textul atunci cand este trimis in mod literal (daca ma exprim corect) catre functia ta, este const. Chiar daca functia ta il primeste non-const. Si cred ca este normal sa primesti "segmentation fault" atunci cand incerci sa modifici un text declarat const.

Motivul pentru care trebuie textul trebuie salvat intr-o variabila pe care o poti modifica. Exemplu:

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

/* Preferably use unsigned integers as index arrays since arrays don't have negative indexes. */
void removeString(char * str, unsigned int pos, unsigned int num)
{
unsigned int len = 0; /* <- NOTE: Calculate the string length after testing against NULL! */

if ((str == NULL) || ((len = strlen(str)) == 0) || /* <- Is there even a string to parse? */
((pos + num) > len)) /* <- Are we in string bounds? */
{
return; /* <- Nothing to parse / Nothing to print */
}

/* Shift values back and leave room for the compiler to optimize */
strncpy(str + (pos), str + (pos+num), len - (pos+num)+1);
/* memcpy(str + (pos), str + (pos+num), (len - (pos+num)+1) * sizeof(char)); */

/* Print result */
printf("-- %s\n", str);
}


int main (void)
{
void removeString(char * str, unsigned int pos, unsigned int num);

/* This fails because the string is constant. And a constant cannot be modified! */
/* removeString("the wrong son", 4, 6); */

printf("Test valid arguments\n");

char str[] = "the wrong son";
removeString(str, 4, 6);

printf("Test empty string\n");

char empty_str[] = "";
removeString(empty_str, 4, 6);

printf("Test null string\n");
removeString(NULL, 4, 6);

printf("Test out of bounds\n");

char bounds_str[] = "the wrong son";
removeString(bounds_str, 27, 5);

printf("Test a single character\n");

char single_str[] = "the wrong son";
removeString(single_str, 5, 1);

printf("Test no character\n");

char none_str[] = "the wrong son";
removeString(none_str, 5, 0);

printf("Test the last character\n");

char last_str[] = "the wrong son";
removeString(last_str, 12, 1);

printf("Test one past the last character\n");

char past_str[] = "the wrong son";
removeString(past_str, 13, 1);

return EXIT_SUCCESS;
}

@MrGrj se refera la:


int main (void)
{
void removeString(char * str, unsigned int pos, unsigned int num);

printf("Test valid arguments\n");

char * str = (char *)malloc(14 * sizeof(char)); /* Allocate memory for 14 characters (including null) */

/* Check the allocated memory */
if (str == NULL)
{
printf("No more memory!");
return EXIT_FAILURE;
}

strcpy(str, "the wrong son"); /* Copy the string into the allocated memory */

removeString(str, 4, 6); /* Deal with it */

free(str); /* Remember to release manually allocated memory */

return EXIT_SUCCESS;
}

Imi cer scuze ca am intervenit si am adaugat exemplul pe care l-ai promis tu.

Edited by S.L.C
Link to comment
Share on other sites

Cand aloci dinamic o variabila se salveaza in heap(ca referinta, pointer) si este retinuta pe tot parcursul rularii programului sau pana este deferentiata(free), in schimb daca aloci static(stack), memoria alocata este eliberata in momentul iesirii din functie( main in cazul de fata).Acum, MrGrj, de ce ai aloca dinamic o variabila avand in vedere ca tu nu folosesti acea variabila in afara functiei main? Eu cred ca este mai degraba BAD PROGRAMMING PRACTICE and we shouldn't use that in this situation.

Edited by Erase
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...