Replace Space to Hyphen

前端 未结 7 1115

I am trying to replace a space character into a hyphen I have in my string.

String replaceText = \"AT AT\";
replaceText.replace(\' \', \'-\');

相关标签:
7条回答
  • 2021-02-18 23:41

    The replace and replaceAll methods return a String with the replaced result. Are you using the returned value, or expecting the replaceText String to change? If it's the latter, you won't see the change, because Strings are immutable.

    String replaceText = "AT AT";
    String replaced = replaceText.replace(' ', '-');
    
    // replaced will be "AT-AT", but replaceText will NOT change
    
    0 讨论(0)
  • 2021-02-18 23:44

    If you are replacing many strings you want to consider using StringBuilder for performance.

    String replaceText = "AT AT";
    StringBuilder sb = new StringBuilder(replaceText);
    sb.Replace(' ', '-');
    
    0 讨论(0)
  • 2021-02-18 23:49
    /*You can use below method pass your String parameter and get result as   String  spaces replaced with hyphen*/
      private static String replaceSpaceWithHypn(String str) {
        if (str != null && str.trim().length() > 0) {
            str = str.toLowerCase();
            String patternStr = "\\s+";
            String replaceStr = "-";
            Pattern pattern = Pattern.compile(patternStr);
            Matcher matcher = pattern.matcher(str);
            str = matcher.replaceAll(replaceStr);
            patternStr = "\\s";
            replaceStr = "-";
            pattern = Pattern.compile(patternStr);
            matcher = pattern.matcher(str);
            str = matcher.replaceAll(replaceStr);
        }
        return str;
    }
    
    0 讨论(0)
  • 2021-02-18 23:50

    Strings are immutable. You need to use the return value from replace:

    replaceText = replaceText.replace(' ', '-');
    
    0 讨论(0)
  • 2021-02-18 23:54

    The replace method returns a String, so you need to re-assign your string variable i.e.

    String replaceText = "AT AT";                         
    replaceText = replaceText.replace(' ', '-'); 
    
    0 讨论(0)
  • 2021-02-19 00:03
    replaceText = replaceText.replace(' ', '-');
    

    Strings are immutable, they cannot be changed after creation. All methods that somehow modify a string will return a new string with the modifications incorporated.

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