Replace Space to Hyphen

前端 未结 7 1156

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: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;
    }
    

提交回复
热议问题