如何用连字符替换空间?

时间:2014-02-17 06:17:33

标签: java replace stringbuffer

我想用“ - ”代替空格

假设我的代码是

StringBuffer tokenstr=new StringBuffer();
tokenstr.append("technician education systems of the Cabinet has approved the following");

我想要输出

"technician-education-systems-of-the-Cabinet-has-approved-the-following"

感谢

7 个答案:

答案 0 :(得分:4)

像这样,

StringBuffer tokenstr = new StringBuffer();
tokenstr.append("technician education systems of the Cabinet has approved the following");
System.out.println(tokenstr.toString().replaceAll(" ", "-"));

也是这样的

System.out.println(tokenstr.toString().replaceAll("\\s+", "-"));

答案 1 :(得分:0)

如果你有StringBuffer对象,那么你需要迭代它并替换字符:

 for (int index = 0; index < tokenstr.length(); index++) {
            if (tokenstr.charAt(index) == ' ') {
                tokenstr.setCharAt(index, '-');
            }
        }

或将其转换为String然后替换如下:

String value = tokenstr.toString().replaceAll(" ", "-");

答案 2 :(得分:0)

这样做

 StringBuffer tokenstr=new StringBuffer();
 tokenstr.append("technician education systems of the Cabinet has approved the following".replace(" ", "-"));
 System.out.print(tokenstr);

答案 3 :(得分:0)

你可以试试这个:

//First store your value in string object and replace space with "-" before appending it to StringBuffer. 
String str = "technician education systems of the Cabinet has approved the following";
str = str.replaceAll(" ", "-");
StringBuffer tokenstr=new StringBuffer();
tokenstr.append(str);
System.out.println(tokenstr);

答案 4 :(得分:0)

您需要编写自定义replaceAll方法。您需要找到src字符串索引并将这些字符串子字符串替换为目标字符串。

请按Jon Skeet

查找代码段

答案 5 :(得分:0)

如果你不想在StringBuffer和String类之间来回跳转,你可以这样做:

StringBuffer tokenstr = new StringBuffer();
tokenstr.append("technician education systems of the Cabinet has approved the following");

int idx=0;
while( idx = tokenstr.indexOf(" ", idx) >= 0 ) {
    tokenstr.replace(idx,idx+1,"-");
}

答案 6 :(得分:0)

/ 您可以使用下面的方法传递您的String参数并获取结果,因为字符串空格替换为连字符 /

 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;
}
相关问题