简体   繁体   English

如何用 int 替换 substring

[英]How to replace substring with int

So i've seen alot of functions like str_replace(str, substr, newstring) but all of them won't work with numbers so i was wondering if anyone had one that would work with both chars and ints or just int ive been looking everywhere and cant figure out a idea on how to write my own.所以我见过很多像 str_replace(str, substr, newstring) 这样的函数,但它们都不能处理数字,所以我想知道是否有人有一个可以同时处理字符和整数的函数,或者只是我一直在到处寻找并且无法弄清楚如何编写自己的想法。 my goal exactly is to be able to replace a string with a int value in the string not just string with string我的目标正是能够用字符串中的 int 值替换字符串,而不仅仅是用字符串替换字符串

below is the function i use to replace strings and it worked just fine下面是我用来替换字符串的 function,它工作得很好

void strrpc(char *target, const char *needle, const char *replacement)
{
    char buffer[1024] = { 0 };
    char *insert_point = &buffer[0];
    const char *tmp = target;
    size_t needle_len = strlen(needle);
    size_t repl_len = strlen(replacement);

    while (1) {
        const char *p = strstr(tmp, needle);

        // walked past last occurrence of needle; copy remaining part
        if (p == NULL) {
            strcpy(insert_point, tmp);
            break;
        }

        // copy part before needle
        memcpy(insert_point, tmp, p - tmp);
        insert_point += p - tmp;

        // copy replacement string
        memcpy(insert_point, replacement, repl_len);
        insert_point += repl_len;

        // adjust pointers, move on
        tmp = p + needle_len;
    }

    // write altered string back to target
    strcpy(target, buffer);
}

You can turn an integer into a string by "printing" it to a string:您可以通过将 integer “打印”到字符串来将其转换为字符串:

int id = get_id();
char idstr[20];

sprintf(idstr, "%d", id);

Now you can现在你可以

char msg[1024] = "Processing item {id} ...";

strrpc(msg, "{id}", idstr);
puts(msg);

But note that the implementation of strrpc you found will work only if the string after replacement is shorter than 1023 character.但请注意,您找到的strrpc的实现只有在替换后的字符串短于 1023 个字符时才有效。 Also note the the example above could more easily be written as just:还要注意上面的例子可以更容易地写成:

printf("Processing item %d ...\n", get_id());

without the danger of buffer overflow.没有缓冲区溢出的危险。 I don't know what exactly you want to achieve, but perhaps string replacement is not the best solution here.我不知道你到底想达到什么,但也许字符串替换不是最好的解决方案。 (Just sayin'.) (只是在说'。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM