用一个字符替换字符串中的多个字符 [英] Replace multiple character in a string with one character

查看:87
本文介绍了用一个字符替换字符串中的多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个字符替换字符串中的多个字符。

示例我有字符串

  8   0495 :< 0x221> [ 7 ]  02   20  4e  65   04  a5 a5 



输出将像

  8   0495 ,0x221, 7  02   20  4e  65   04  a5 a5 





而不是一个一个地替换



我尝试过:



我将分别替换每个字符,

解决方案

一些建议:字符串替换c - Google搜索 [ ^ ]。


这可能是效率最高的。



  char 数据[ ] =   8 0495:< 0x221> [7] 02 20 4e 65 04 a5 a5; 

静态 void replace( char * data)
{
const char * cursor = data;
while (* cursor)
{
// 替换第一个模式
如果(memcmp(cursor, :< 3 )== 0
{
cursor + = 3 ;
* data ++ = ' ,';
}
// 替换第二种模式
else if (memcmp(cursor, > [, 3 )== 0
{
cursor + = 3 ;
* data ++ = ' ,';
}
// 替换第三种模式
else if (memcmp(cursor, ] 2 )== 0
{
cursor + = 2 ;
* data ++ = ' ,';
}
else
{
cursor ++;
data ++;
}
}
* data ++ = 0 ;
}





如果你喜欢使用STL字符串,试试这个:



string :: replace - C ++ Reference [ ^ ]


您可以使用其他动态数组,并保存字符串中所有字符的索引号,并用','替换所有字符。


I want to replace multiple character in the string with one character.
Example I have string

8 0495: <0x221> [7] 02 20 4e 65 04 a5 a5


output would be like

8 0495,0x221,7,02 20 4e 65 04 a5 a5



rather than replacing one by one

What I have tried:

I am replacing each character separately with ,

解决方案

Some suggestions: string replace c - Google Search[^].


This is probably the most efficient.

char data[] = "8 0495: <0x221> [7] 02 20 4e 65 04 a5 a5";

static void replace(char *data)
{
    const char *cursor = data;
    while (*cursor)
    {
        // replace first pattern
        if ( memcmp(cursor, ": <", 3) == 0)
        {
            cursor += 3;
            *data++ = ',';
        }
        // replace second pattern
        else if ( memcmp(cursor, "> [", 3) == 0)
        {
            cursor += 3;
            *data++ = ',';
        }
        // replace third pattern
        else if ( memcmp(cursor, "] ", 2) == 0)
        {
            cursor += 2;
            *data++ = ',';
        }
        else
        {
            cursor++;
            data++;
        } 
    }
    *data++ = 0;
}



If you prefer to work with STL strings, try this:

string::replace - C++ Reference[^]


You can use another dynamic array, and save the index number of all of the characters in the string and replace all of them once by ' , '.


这篇关于用一个字符替换字符串中的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆