एक ( char *) स्ट्रिंग को देखते हुए , मैं सबस्ट्रिंग की सभी घटनाओं को खोजना चाहता हूं और उन्हें वैकल्पिक स्ट्रिंग के साथ बदलना चाहता हूं। मुझे ऐसा कोई सरल कार्य नहीं दिखता जो इसमें प्राप्त करता हो <string.h>।
एक ( char *) स्ट्रिंग को देखते हुए , मैं सबस्ट्रिंग की सभी घटनाओं को खोजना चाहता हूं और उन्हें वैकल्पिक स्ट्रिंग के साथ बदलना चाहता हूं। मुझे ऐसा कोई सरल कार्य नहीं दिखता जो इसमें प्राप्त करता हो <string.h>।
जवाबों:
आशावादी को अधिकांश स्थानीय चरों को समाप्त करना चाहिए। Tmp पॉइंटर यह सुनिश्चित करने के लिए है कि अशक्त को अशक्त खोजने के लिए स्ट्रिंग नहीं चलना है। tmp प्रत्येक कॉल के बाद परिणाम के अंत तक इंगित करता है। (देखें कि शल्कील चित्रकार के एल्गोरिथ्म के लिए कि स्ट्रैची क्यों कष्टप्रद हो सकता है।)
// You must free the result if result is non-NULL.
char *str_replace(char *orig, char *rep, char *with) {
char *result; // the return string
char *ins; // the next insert point
char *tmp; // varies
int len_rep; // length of rep (the string to remove)
int len_with; // length of with (the string to replace rep with)
int len_front; // distance between rep and end of last rep
int count; // number of replacements
// sanity checks and initialization
if (!orig || !rep)
return NULL;
len_rep = strlen(rep);
if (len_rep == 0)
return NULL; // empty rep causes infinite loop during count
if (!with)
with = "";
len_with = strlen(with);
// count the number of replacements needed
ins = orig;
for (count = 0; tmp = strstr(ins, rep); ++count) {
ins = tmp + len_rep;
}
tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1);
if (!result)
return NULL;
// first time through the loop, all the variable are set correctly
// from here on,
// tmp points to the end of the result string
// ins points to the next occurrence of rep in orig
// orig points to the remainder of orig after "end of rep"
while (count--) {
ins = strstr(orig, rep);
len_front = ins - orig;
tmp = strncpy(tmp, orig, len_front) + len_front;
tmp = strcpy(tmp, with) + len_with;
orig += len_front + len_rep; // move to next "end of rep"
}
strcpy(tmp, orig);
return result;
}
size_tबजाय का उपयोग intकरें। इसके अलावा, strcpy(tmp, orig);बहुत अंत में क्या उद्देश्य है ? यह गलत लगता है।
forलूप को बदल सकते हैं for (count = 1; ins = strstr(ins + rep_len, rep); ++count) {}, फिर tmpकेवल लिखने के लिए उपयोग किया जाता है।
यह मानक C लाइब्रेरी में प्रदान नहीं किया गया है, क्योंकि केवल एक char * दिया गया है आप स्ट्रिंग को आवंटित मेमोरी को बढ़ा नहीं सकते हैं यदि प्रतिस्थापन स्ट्रिंग स्ट्रिंग की तुलना में लंबा है।
आप इसका उपयोग std :: string को अधिक आसानी से कर सकते हैं, लेकिन वहां भी, कोई भी फ़ंक्शन आपके लिए ऐसा नहीं करेगा।
वहाँ एक नहीं है।
आपको स्ट्रैस और स्ट्रैकट या स्ट्रैसी जैसी किसी चीज़ का उपयोग करके अपना रोल करना होगा ।
strcat()एक बुरा सुझाव है।
आप एक नया बफर के कुछ हिस्सों में कॉपी करने के लिए सबस्ट्रिंग और strncpy खोजने के लिए स्ट्रैस का उपयोग करके अपने स्वयं के बदले हुए फ़ंक्शन का निर्माण कर सकते हैं।
जब तक आप जो चाहते हैं replace_withवह वही लंबाई है जैसा आप चाहते हैं replace, तो शायद नई स्ट्रिंग का उपयोग करने के लिए नए बफर का उपयोग करना सबसे अच्छा है।
जैसा कि C में तार गतिशील रूप से विकसित नहीं हो सकते हैं प्रतिस्थापन प्रतिस्थापन आमतौर पर काम नहीं करेगा। इसलिए आपको एक नए स्ट्रिंग के लिए जगह आवंटित करने की आवश्यकता है जिसमें आपके प्रतिस्थापन के लिए पर्याप्त जगह है और फिर मूल प्लस से प्रतिस्थापन को नए स्ट्रिंग में भागों की प्रतिलिपि बनाएँ। भागों कॉपी करने के लिए आप का प्रयोग करेंगे strncpy ।
यहाँ कुछ नमूना कोड है जो यह करता है।
#include <string.h>
#include <stdlib.h>
char * replace(
char const * const original,
char const * const pattern,
char const * const replacement
) {
size_t const replen = strlen(replacement);
size_t const patlen = strlen(pattern);
size_t const orilen = strlen(original);
size_t patcnt = 0;
const char * oriptr;
const char * patloc;
// find how many times the pattern occurs in the original string
for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
patcnt++;
}
{
// allocate memory for the new string
size_t const retlen = orilen + patcnt * (replen - patlen);
char * const returned = (char *) malloc( sizeof(char) * (retlen + 1) );
if (returned != NULL)
{
// copy the original string,
// replacing all the instances of the pattern
char * retptr = returned;
for (oriptr = original; patloc = strstr(oriptr, pattern); oriptr = patloc + patlen)
{
size_t const skplen = patloc - oriptr;
// copy the section until the occurence of the pattern
strncpy(retptr, oriptr, skplen);
retptr += skplen;
// copy the replacement
strncpy(retptr, replacement, replen);
retptr += replen;
}
// copy the rest of the string.
strcpy(retptr, oriptr);
}
return returned;
}
}
#include <stdio.h>
int main(int argc, char * argv[])
{
if (argc != 4)
{
fprintf(stderr,"usage: %s <original text> <pattern> <replacement>\n", argv[0]);
exit(-1);
}
else
{
char * const newstr = replace(argv[1], argv[2], argv[3]);
if (newstr)
{
printf("%s\n", newstr);
free(newstr);
}
else
{
fprintf(stderr,"allocation error\n");
exit(-2);
}
}
return 0;
}
// Here is the code for unicode strings!
int mystrstr(wchar_t *txt1,wchar_t *txt2)
{
wchar_t *posstr=wcsstr(txt1,txt2);
if(posstr!=NULL)
{
return (posstr-txt1);
}else
{
return -1;
}
}
// assume: supplied buff is enough to hold generated text
void StringReplace(wchar_t *buff,wchar_t *txt1,wchar_t *txt2)
{
wchar_t *tmp;
wchar_t *nextStr;
int pos;
tmp=wcsdup(buff);
pos=mystrstr(tmp,txt1);
if(pos!=-1)
{
buff[0]=0;
wcsncpy(buff,tmp,pos);
buff[pos]=0;
wcscat(buff,txt2);
nextStr=tmp+pos+wcslen(txt1);
while(wcslen(nextStr)!=0)
{
pos=mystrstr(nextStr,txt1);
if(pos==-1)
{
wcscat(buff,nextStr);
break;
}
wcsncat(buff,nextStr,pos);
wcscat(buff,txt2);
nextStr=nextStr+pos+wcslen(txt1);
}
}
free(tmp);
}
Repl_str () creativeandcritical.net पर समारोह तेजी से और विश्वसनीय है। इसके अलावा उस पृष्ठ पर शामिल एक विस्तृत स्ट्रिंग संस्करण, repl_wcs () है , जो यूटीएफ -8 में एन्कोड किए गए सहित यूनिकोड स्ट्रिंग्स के साथ उपयोग किया जा सकता है, सहायक कार्यों के माध्यम से - डेमो कोड पृष्ठ से जुड़ा हुआ है। पूर्ण प्रकटीकरण से संबंधित: मैं उस पृष्ठ का लेखक और उस पर कार्य करता हूं।
pos_cache = realloc(pos_cache
free(pos_cache);फ़ंक्शन अंत में बचता है ।
reallocविफल हो सकता है। यदि ऐसा होता है, तो यह वापस लौटता है NULLऔर पुराने सूचक को बरकरार रखता है। p = realloc(p, x)इच्छाशक्ति विफल होने पर, एक मान्य हीप पॉइंटर pको फिर से लिखें NULL, और यदि यह pआपके उस हीप ऑब्जेक्ट का एकमात्र संदर्भ था, तो अब आपने इसे लीक कर दिया है। यह एक क्लासिक नौसिखिया गलती है।
मुझे अधिकांश प्रस्तावित कार्य समझने में कठिन लगे - इसलिए मैं इसके साथ आया:
static char *dull_replace(const char *in, const char *pattern, const char *by)
{
size_t outsize = strlen(in) + 1;
// TODO maybe avoid reallocing by counting the non-overlapping occurences of pattern
char *res = malloc(outsize);
// use this to iterate over the output
size_t resoffset = 0;
char *needle;
while (needle = strstr(in, pattern)) {
// copy everything up to the pattern
memcpy(res + resoffset, in, needle - in);
resoffset += needle - in;
// skip the pattern in the input-string
in = needle + strlen(pattern);
// adjust space for replacement
outsize = outsize - strlen(pattern) + strlen(by);
res = realloc(res, outsize);
// copy the pattern
memcpy(res + resoffset, by, strlen(by));
resoffset += strlen(by);
}
// copy the remaining input
strcpy(res + resoffset, in);
return res;
}
उत्पादन मुक्त होना चाहिए
आप इस फ़ंक्शन का उपयोग कर सकते हैं (टिप्पणियां बताती हैं कि यह कैसे काम करता है):
void strreplace(char *string, const char *find, const char *replaceWith){
if(strstr(string, replaceWith) != NULL){
char *temporaryString = malloc(strlen(strstr(string, find) + strlen(find)) + 1);
strcpy(temporaryString, strstr(string, find) + strlen(find)); //Create a string with what's after the replaced part
*strstr(string, find) = '\0'; //Take away the part to replace and the part after it in the initial string
strcat(string, replaceWith); //Concat the first part of the string with the part to replace with
strcat(string, temporaryString); //Concat the first part of the string with the part after the replaced part
free(temporaryString); //Free the memory to avoid memory leaks
}
}
यहाँ एक है जो मैंने इन आवश्यकताओं के आधार पर बनाया है:
पैटर्न लंबा या छोटा है, इसकी परवाह किए बिना।
आंतरिक लीक से बचने के लिए किसी भी मॉलोक (स्पष्ट या निहित) का उपयोग न करें।
पैटर्न की घटनाओं की किसी भी संख्या को बदलें।
प्रतिस्थापित स्ट्रिंग को खोजें स्ट्रिंग के बराबर एक स्ट्रिंग में रखें।
यह जांचने के लिए नहीं है कि प्रतिस्थापन को पकड़ने के लिए लाइन सरणी आकार में पर्याप्त है। उदा। यह तब तक काम नहीं करता है जब तक कि कॉलर को पता न हो कि नई स्ट्रिंग धारण करने के लिए लाइन पर्याप्त आकार की है।
/* returns number of strings replaced.
*/
int replacestr(char *line, const char *search, const char *replace)
{
int count;
char *sp; // start of pattern
//printf("replacestr(%s, %s, %s)\n", line, search, replace);
if ((sp = strstr(line, search)) == NULL) {
return(0);
}
count = 1;
int sLen = strlen(search);
int rLen = strlen(replace);
if (sLen > rLen) {
// move from right to left
char *src = sp + sLen;
char *dst = sp + rLen;
while((*dst = *src) != '\0') { dst++; src++; }
} else if (sLen < rLen) {
// move from left to right
int tLen = strlen(sp) - sLen;
char *stop = sp + rLen;
char *src = sp + sLen + tLen;
char *dst = sp + rLen + tLen;
while(dst >= stop) { *dst = *src; dst--; src--; }
}
memcpy(sp, replace, rLen);
count += replacestr(sp + rLen, search, replace);
return(count);
}
इस कोड को बेहतर बनाने के किसी भी सुझाव को सहर्ष स्वीकार कर लिया गया है। बस टिप्पणी पोस्ट करें और मैं इसका परीक्षण करूंगा।
आप स्ट्रेप () का उपयोग कर सकते हैं
char * strrep (कास्ट char * Cadena, कास्ट char * strf, const char * strr)
strrep (स्ट्रिंग बदलें)। 'स्ट्रै ’को' कैडर’ में r एसआरआर ’से बदल देता है और नया स्ट्रिंग लौटाता है। स्ट्रेप का उपयोग करने के बाद आपको अपने कोड में दिए गए स्ट्रिंग को मुक्त करना होगा।
पैरामीटर कैडेना पाठ के साथ स्ट्रिंग। पाठ खोजने के लिए। strr प्रतिस्थापन पाठ।
रिटर्न पाठ अद्यतन प्रतिस्थापन को मिटा देता है।
परियोजना https://github.com/ipserc/strrep पर देखी जा सकती है
स्ट्रिंग के इन-प्लेस संशोधन का उपयोग करके fann95 की प्रतिक्रिया के लिए एक फिक्स, और लाइन द्वारा इंगित बफर को संभालने के परिणामस्वरूप परिणामी स्ट्रिंग को पकड़ने के लिए पर्याप्त है।
static void replacestr(char *line, const char *search, const char *replace)
{
char *sp;
if ((sp = strstr(line, search)) == NULL) {
return;
}
int search_len = strlen(search);
int replace_len = strlen(replace);
int tail_len = strlen(sp+search_len);
memmove(sp+replace_len,sp+search_len,tail_len+1);
memcpy(sp, replace, replace_len);
}
वहाँ तुम जाओ .... यह चरित्र स्ट्रिंग के भीतर के char xसाथ हर संभावना को बदलने के लिए समारोह हैchar ystr
char *zStrrep(char *str, char x, char y){
char *tmp=str;
while(*tmp)
if(*tmp == x)
*tmp++ = y; /* assign first, then incement */
else
*tmp++;
*tmp='\0';
return str;
}
एक उदाहरण उपयोग हो सकता है
Exmaple Usage
char s[]="this is a trial string to test the function.";
char x=' ', y='_';
printf("%s\n",zStrrep(s,x,y));
Example Output
this_is_a_trial_string_to_test_the_function.
फ़ंक्शन एक स्ट्रिंग लाइब्रेरी से है जिसे मैं गितुब पर रखता हूं , आप अन्य उपलब्ध कार्यों पर एक नज़र रखने या यहां तक कि कोड में योगदान करने के लिए स्वागत से अधिक हैं :)
https://github.com/fnoyanisi/zString
संपादित करें: @ साइराइड सही है, ऊपर फ़ंक्शन केवल वर्णों को बदलता है। बस यह एक लिखा है, जो चरित्र तार की जगह लेता है।
#include <stdio.h>
#include <stdlib.h>
/* replace every occurance of string x with string y */
char *zstring_replace_str(char *str, const char *x, const char *y){
char *tmp_str = str, *tmp_x = x, *dummy_ptr = tmp_x, *tmp_y = y;
int len_str=0, len_y=0, len_x=0;
/* string length */
for(; *tmp_y; ++len_y, ++tmp_y)
;
for(; *tmp_str; ++len_str, ++tmp_str)
;
for(; *tmp_x; ++len_x, ++tmp_x)
;
/* Bounds check */
if (len_y >= len_str)
return str;
/* reset tmp pointers */
tmp_y = y;
tmp_x = x;
for (tmp_str = str ; *tmp_str; ++tmp_str)
if(*tmp_str == *tmp_x) {
/* save tmp_str */
for (dummy_ptr=tmp_str; *dummy_ptr == *tmp_x; ++tmp_x, ++dummy_ptr)
if (*(tmp_x+1) == '\0' && ((dummy_ptr-str+len_y) < len_str)){
/* Reached end of x, we got something to replace then!
* Copy y only if there is enough room for it
*/
for(tmp_y=y; *tmp_y; ++tmp_y, ++tmp_str)
*tmp_str = *tmp_y;
}
/* reset tmp_x */
tmp_x = x;
}
return str;
}
int main()
{
char s[]="Free software is a matter of liberty, not price.\n"
"To understand the concept, you should think of 'free' \n"
"as in 'free speech', not as in 'free beer'";
printf("%s\n\n",s);
printf("%s\n",zstring_replace_str(s,"ree","XYZ"));
return 0;
}
और नीचे आउटपुट है
Free software is a matter of liberty, not price.
To understand the concept, you should think of 'free'
as in 'free speech', not as in 'free beer'
FXYZ software is a matter of liberty, not price.
To understand the concept, you should think of 'fXYZ'
as in 'fXYZ speech', not as in 'fXYZ beer'
/*замена символа в строке*/
char* replace_char(char* str, char in, char out) {
char * p = str;
while(p != '\0') {
if(*p == in)
*p == out;
++p;
}
return str;
}
DWORD ReplaceString(__inout PCHAR source, __in DWORD dwSourceLen, __in const char* pszTextToReplace, __in const char* pszReplaceWith)
{
DWORD dwRC = NO_ERROR;
PCHAR foundSeq = NULL;
PCHAR restOfString = NULL;
PCHAR searchStart = source;
size_t szReplStrcLen = strlen(pszReplaceWith), szRestOfStringLen = 0, sztextToReplaceLen = strlen(pszTextToReplace), remainingSpace = 0, dwSpaceRequired = 0;
if (strcmp(pszTextToReplace, "") == 0)
dwRC = ERROR_INVALID_PARAMETER;
else if (strcmp(pszTextToReplace, pszReplaceWith) != 0)
{
do
{
foundSeq = strstr(searchStart, pszTextToReplace);
if (foundSeq)
{
szRestOfStringLen = (strlen(foundSeq) - sztextToReplaceLen) + 1;
remainingSpace = dwSourceLen - (foundSeq - source);
dwSpaceRequired = szReplStrcLen + (szRestOfStringLen);
if (dwSpaceRequired > remainingSpace)
{
dwRC = ERROR_MORE_DATA;
}
else
{
restOfString = CMNUTIL_calloc(szRestOfStringLen, sizeof(CHAR));
strcpy_s(restOfString, szRestOfStringLen, foundSeq + sztextToReplaceLen);
strcpy_s(foundSeq, remainingSpace, pszReplaceWith);
strcat_s(foundSeq, remainingSpace, restOfString);
}
CMNUTIL_free(restOfString);
searchStart = foundSeq + szReplStrcLen; //search in the remaining str. (avoid loops when replWith contains textToRepl
}
} while (foundSeq && dwRC == NO_ERROR);
}
return dwRC;
}
char *replace(const char*instring, const char *old_part, const char *new_part)
{
#ifndef EXPECTED_REPLACEMENTS
#define EXPECTED_REPLACEMENTS 100
#endif
if(!instring || !old_part || !new_part)
{
return (char*)NULL;
}
size_t instring_len=strlen(instring);
size_t new_len=strlen(new_part);
size_t old_len=strlen(old_part);
if(instring_len<old_len || old_len==0)
{
return (char*)NULL;
}
const char *in=instring;
const char *found=NULL;
size_t count=0;
size_t out=0;
size_t ax=0;
char *outstring=NULL;
if(new_len> old_len )
{
size_t Diff=EXPECTED_REPLACEMENTS*(new_len-old_len);
size_t outstring_len=instring_len + Diff;
outstring =(char*) malloc(outstring_len);
if(!outstring){
return (char*)NULL;
}
while((found = strstr(in, old_part))!=NULL)
{
if(count==EXPECTED_REPLACEMENTS)
{
outstring_len+=Diff;
if((outstring=realloc(outstring,outstring_len))==NULL)
{
return (char*)NULL;
}
count=0;
}
ax=found-in;
strncpy(outstring+out,in,ax);
out+=ax;
strncpy(outstring+out,new_part,new_len);
out+=new_len;
in=found+old_len;
count++;
}
}
else
{
outstring =(char*) malloc(instring_len);
if(!outstring){
return (char*)NULL;
}
while((found = strstr(in, old_part))!=NULL)
{
ax=found-in;
strncpy(outstring+out,in,ax);
out+=ax;
strncpy(outstring+out,new_part,new_len);
out+=new_len;
in=found+old_len;
}
}
ax=(instring+instring_len)-in;
strncpy(outstring+out,in,ax);
out+=ax;
outstring[out]='\0';
return outstring;
}
यह फ़ंक्शन केवल तभी काम करता है जब उर स्ट्रिंग में नई लंबाई के लिए अतिरिक्त स्थान हो
void replace_str(char *str,char *org,char *rep)
{
char *ToRep = strstr(str,org);
char *Rest = (char*)malloc(strlen(ToRep));
strcpy(Rest,((ToRep)+strlen(org)));
strcpy(ToRep,rep);
strcat(ToRep,Rest);
free(Rest);
}
यह केवल पहली घटना की जगह लेता है
यहाँ मेरा जाता है, यह स्वयं निहित और बहुमुखी है, साथ ही कुशल है, यह प्रत्येक पुनरावृत्ति में आवश्यकतानुसार बफ़र्स बढ़ता या सिकुड़ता है
void strreplace(char *src, char *str, char *rep)
{
char *p = strstr(src, str);
if (p)
{
int len = strlen(src)+strlen(rep)-strlen(str);
char r[len];
memset(r, 0, len);
if ( p >= src ){
strncpy(r, src, p-src);
r[p-src]='\0';
strncat(r, rep, strlen(rep));
strncat(r, p+strlen(str), p+strlen(str)-src+strlen(src));
strcpy(src, r);
strreplace(p+strlen(rep), str, rep);
}
}
}
यहाँ मेरा जाता है, उन्हें सभी चार * बनाओ, जो कॉलिंग को आसान बनाता है ...
char *strrpc(char *str,char *oldstr,char *newstr){
char bstr[strlen(str)];
memset(bstr,0,sizeof(bstr));
int i;
for(i = 0;i < strlen(str);i++){
if(!strncmp(str+i,oldstr,strlen(oldstr))){
strcat(bstr,newstr);
i += strlen(oldstr) - 1;
}else{
strncat(bstr,str + i,1);
}
}
strcpy(str,bstr);
return str;
}
String.h से केवल strlen का उपयोग करना
मेरी अंग्रेजी के लिए खेद है
char * str_replace(char * text,char * rep, char * repw){//text -> to replace in it | rep -> replace | repw -> replace with
int replen = strlen(rep),repwlen = strlen(repw),count;//some constant variables
for(int i=0;i<strlen(text);i++){//search for the first character from rep in text
if(text[i] == rep[0]){//if it found it
count = 1;//start searching from the next character to avoid repetition
for(int j=1;j<replen;j++){
if(text[i+j] == rep[j]){//see if the next character in text is the same as the next in the rep if not break
count++;
}else{
break;
}
}
if(count == replen){//if count equals to the lenght of the rep then we found the word that we want to replace in the text
if(replen < repwlen){
for(int l = strlen(text);l>i;l--){//cuz repwlen greater than replen we need to shift characters to the right to make space for the replacement to fit
text[l+repwlen-replen] = text[l];//shift by repwlen-replen
}
}
if(replen > repwlen){
for(int l=i+replen-repwlen;l<strlen(text);l++){//cuz replen greater than repwlen we need to shift the characters to the left
text[l-(replen-repwlen)] = text[l];//shift by replen-repwlen
}
text[strlen(text)-(replen-repwlen)] = '\0';//get rid of the last unwanted characters
}
for(int l=0;l<repwlen;l++){//replace rep with repwlen
text[i+l] = repw[l];
}
if(replen != repwlen){
i+=repwlen-1;//pass to the next character | try text "y" ,rep "y",repw "yy" without this line to understand
}
}
}
}
return text;
}
यदि आप string.h को कॉल करने से बचने के लिए strlen कोड चाहते हैं
int strlen(char * string){//use this code to avoid calling string.h
int lenght = 0;
while(string[lenght] != '\0'){
lenght++;
}
return lenght;
}