【问题标题】:String manipulation in C (replace & insert characters)C 中的字符串操作(替换和插入字符)
【发布时间】:2013-12-09 07:51:00
【问题描述】:

我是 C 的新手,我对 sprintf 知之甚少,但我无法满足我的要求。

我有一个 char * 变量,其中包含如下字符串:

date=2013-12-09 time=07:31:10 d_id=device1 logid=01  user=user1 lip=1.1.1.1 mac=00:11:22:33:44:55 cip=2.2.2.2 dip=3.3.3.3 proto=AA sport=22 dport=11 in_1=eth1 out_1=

我想要一个输出

2013-12-09#07:31:10#device1#01#user1#1.1.1.1#00:11:22:33:44:55#2.2.2.2#3.3.3.3#AA#22#11#eth1##

如果某个值在= 之后为空,它应该按顺序打印##

【问题讨论】:

  • 给出一些你试过的代码。

标签: c string printf


【解决方案1】:

我不会给你确切的代码,但我会给你一些对你有帮助的链接。

strchr:: 你可以用这个找到'='在字符串中的位置。

  1. 现在,复制“=”位置之后的字符串,直到找到一个“空格”。
  2. 只要找到“空格”,就在缓冲区中写入“#”。
  3. 继续这样做,直到遇到“\0”。遇到 '\0' 时将 '##' 写入缓冲区
  4. 附加一个“\0”。

例如:: C function strchr - How to calculate the position of the character?

【讨论】:

    【解决方案2】:

    使用 strtok、strchr、sprintf 的示例

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main(){
        const char *data = "date=2013-12-09 time=07:31:10 d_id=device1 logid=01  user=user1 lip=1.1.1.1 mac=00:11:22:33:44:55 cip=2.2.2.2 dip=3.3.3.3 proto=AA sport=22 dport=11 in_1=eth1 out_1=";
        char *work = strdup(data);//make copy for work
        char *output = strdup(data);//allocate for output
        char *assignment; //tokenize to aaa=vvv
        size_t o_count = 0;//output number of character count
        for(assignment=strtok(work, " "); assignment ;assignment=strtok(NULL, " ")){
            o_count += sprintf(output + o_count, "%s#", strchr(assignment, '=')+1);
        }
        printf("%s", output);
        free(work);
        free(output);
        return 0;
    }
    

    【讨论】:

    • for(assignment=strtok(work, " "); assignment ;assignment=strtok(NULL, " ")){ o_count += sprintf(output + o_count, "%s#", strchr(赋值,'=')+1); } 这行有时会出现段错误!
    • @user95711 没有问题,但是不要还是直接操作字符串?
    • o_count += sprintf(output + o_count, "%s#", strchr(assignment, '=')+1);这里发生了一些错误。 n 是的,我正在按照您的建议进行操作。
    • @user95711 包含'='的前提总是token,但是格式是这样还是已经变成这样了?有必要通过提前检查来跳过标记,因为它会导致分段错误,只要存在不包含它的情况是 if '='。
    • @user95711 是否可以在出错的情况下呈现数据?
    猜你喜欢
    • 2010-09-10
    • 2019-06-21
    • 1970-01-01
    • 2011-10-20
    • 2014-07-30
    • 1970-01-01
    • 2021-09-26
    • 2018-04-02
    • 1970-01-01
    相关资源
    最近更新 更多