字符串操作-还有其他有效的方法吗? [英] String manipulation - Any other efficient way?

查看:42
本文介绍了字符串操作-还有其他有效的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我需要在出现单引号(')的地方在给定的字符串变量中插入转义序列.我尝试使用 split 方法以及 StringTokenizer ,但都没有一个适合我.因此,我开发了以下提到的逻辑.在某些情况下也会失败

I had a requirement where i need to insert an escape sequence in a given string variable, at places wherever a single quotes (') appears. I tried using split method and also StringTokenizer, neither one worked out for me. So i developed the below mentioned logic. It also fails in a few scenarios

任何人都可以为我提供实现这一要求的最简单方法吗?

Can anyone provide me a simplest way to achieve such requirement.?

public static String quotesMessage(String message){
    String newMessage="";
    while(message.length()>0){
        if(message.indexOf("'")==0){
            if(!StringUtils.isEmpty(message.substring(0))){
                message = message.substring(1);
            }
        }else{
            if(message.indexOf("'")!= -1){
                newMessage=newMessage+message.substring(0,message.indexOf("'"))+"\\'";
                message=message.substring(message.indexOf("'"));
            }else{
                newMessage=newMessage+message;
                message="";
            }
        }
    }
    return newMessage;
}

推荐答案

如何操作:

newMessage.replace("'", "\\'")

还是我误会了您的要求?

Or do I misunderstand your requirement?

关于注释中的讨论:是的, replace() replaceAll() 都使用正则表达式在内部使用了已编译的模式(但是 replace()使用标志 Pattern.LITERAL ),将模式解释为文字值,而 replaceAll()(和 replaceFirst())都使用正则表达式.但是,编译的模式是绝对相同的(在这种情况下).自己尝试:

And about the discussions in comments: yes, both replace() and replaceAll() use Regular Expressions use compiled Patterns internally (but replace() uses the flag Pattern.LITERAL), interpreting the pattern as literal value, whereas replaceAll() (and replaceFirst()) both use Regular Expressions. However, the compiled patterns are absolutely identical (in this case). Try it yourself:

Pattern literal = Pattern.compile("'",Pattern.LITERAL);
Pattern regular = Pattern.compile("'");

在这些分配之后添加一个断点,并仔细查看这两个编译模式.您会发现它们的所有字段值都相同,因此至少在这种情况下,不会对性能产生任何影响.

Add a breakpoint after these assignments and take a closer look at these two compiled patterns. You will find that all of their field values are identical, so in this case at least, no it doesn't make any difference performance-wise.

这篇关于字符串操作-还有其他有效的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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