Google是你的朋友。這是搜索查詢的第一個命中:「c替代字符串」。你需要什麼權利在這裏:What is the function to replace string in C?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(){
char fileName[80];
printf("Please enter filename: ");
scanf("%s", fileName);
char outName[];
printf("Outputname: %s\n", replace(filename,".txt","_out.txt"));
}
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;
}
}
這有什麼錯用'海峽{,N} {CPY,貓}()'? –
是的,有一種方法可以做到這一點。我們還能怎樣幫助你?問:「可能嗎?」或「有沒有辦法?」除了說「是的,是」或者「不是,這不是對任何人都沒有幫助」之外,在這裏不應該承擔責任。請[編輯]你的問題,使其更具體。 –
這似乎是在這裏解決:http://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c – carlosdc