How to replace || (two pipes) from a string with | (one) pipe

后端 未结 5 1557
醉话见心
醉话见心 2021-01-15 00:24

I am getting response for some images in json format within this tag:

\"xmlImageIds\":\"57948916||57948917||57948918||57948919||57948920||57948921||57

相关标签:
5条回答
  • 2021-01-15 00:40

    I think I know what your problem is. You need to assign the result of replace(), not just call it.

    String s = "foo||bar||baz";
    s = s.replace("||", "|");
    System.out.println(s);
    

    I tested it, and just calling s.replace("||", "|"); doesn't seem to modify the string; you have to assign that result back to s.

    Edit: The Java 6 spec says "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar." (the emphasis is mine).

    0 讨论(0)
  • 2021-01-15 00:40
        String pipe="pipes||";
        System.out.println("Old Pipe:::"+pipe);
        System.out.println("Updated Pipe:::"+pipe.replace("||", "|"));
    
    0 讨论(0)
  • 2021-01-15 00:41

    According to http://docs.oracle.com/javase/6/docs/api/java/lang/String.html, replace() takes chars instead of Strings. Perhaps you should try replaceAll(String, String) instead? Either that, or try changing your String ("") quotation marks into char ('') quotation marks.

    Edit: I just noticed the overload for replace() that takes a CharSequence. I'd still give replaceAll() a try though.

    0 讨论(0)
  • 2021-01-15 00:47

    Use

    .replace("||", "|");
    

    | is no special char.

    However, if you are using split() or replaceAll instead of replace(), beware that you need to escape the pipe symbol as \\|, because these methods take a regex as parameter.

    For example:

    public static void main(String[] args) {
        String in = "\"xmlImageIds\":\"57948916||57948917||57948918||57948919||57948920||57948921||57948‌922||57948923||57948924||57948925||57948926||5794892\"".replace("||", "|");
    
        String[] q = in.split("\"");
        String[] ids = q[3].split("\\|");
        for (String id : ids) {
            System.out.println("http://test/" + id);
        }
    }
    
    0 讨论(0)
  • 2021-01-15 00:51

    i dont remember how it works that method... but you can make your own:

    String withTwoPipes = "helloTwo||pipes";
       for(int i=0; i<withTwoPipes.lenght;i++){
          char a = withTwoPipes.charAt(i);
          if(a=='|' && i<withTwoPipes.lenght+1){
             char b = withTwoPipes.charAt(i+1);
             if(b=='|' && i<withTwoPipes.lenght){
               withTwoPipes.charAt(i)='';
               withTwoPipes.charAt(i+1)='|';
             }
          }
       }
    

    I think that some code like this should work... its not a perfect answer but can help...

    0 讨论(0)
提交回复
热议问题