Input two strings str1 and str2, judge whether str2 str1 substring, if yes, please delete the str1 substring str2 after part of the output (note: if the str1 contains multiple str2 substring, only will be deleted in the str1 the rightmost part of the output after a substring)
Novice c language, for arrays and strings don't quite understand this, for advice
CodePudding user response:
STRSTR function is to find any substring, calls to find the last clause! For example
int delstr (char * str1, char * str2) { If (str1==NULL | | str2==NULL) return 0; Int len1=(int) strlen (str1), len2=(int) strlen (str2); If (len1 & lt; Len2) return 0; Else if (len2==0) return 1;
P1=str1, char * * p2=str1;//the code above is normal data, can be ignored, start from here is the main code While ((p1=STRSTR (p1, str2))!=NULL) {//STRSTR couldn't find a substring the return value is NULL, or to find the position of the substring P1 p2=;//records to find the location of the P1 +=len2;//modify the next search start } If (p2==str1) return 0;//if the substring didn't find the return Strcpy (p2, p2 + len2); Starting from the last//find position, after the length of string to copy over * (str1 + len1 - len2)='\ 0';//modify the final string terminator return 1; }
Int main (int arg c, const char * argv []) { Char str1 []={" abcdabcdab "}; Char str2 []={" CD "}; Delstr (str1, str2); Printf (" % s \ n ", str1); return 0; }
CodePudding user response:
STRSTR function, the search string in another position, can't find the return NULL Starting from the str1 last str2 long string such as comparison, continue to move forward one character at a time don't match, know, or reach the head so far The problem now for a few days to have seen the same problems
Int delstr (char * str1, char * str2) { If (str1==NULL | | str2==NULL) return 0; Int len1=(int) strlen (str1), len2=(int) strlen (str2); If (len1 & lt; Len2) return 0; Else if (len2==0) return 1; Char * p=str1 + len1 len2;//positioning to the str1 len2 last the length of the string While (p & gt;=str1) {//not end If (p==STRSTR (p, str2)) break;//from the back forward gradually find, if found will be the current pointer P -; } If (p & lt; Str1) return 0;//if the substring didn't find the return
Strcpy (p, p + len2); Starting from the last//find position, after the length of string to copy over * (str1 + len1 - len2)='\ 0';//modify the final string terminator return 1; }