2014-02-17 194 views
-4

我要替換空間 「 - 」 有什麼辦法如何用連字符替換空格?

假設我的代碼

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" 

感謝

+0

您可以使用String.replace全部()' – user2573153

+0

@ user2573153我正在使用Stringbuffer而不是字符串。 – Adi

+5

你嘗試過什麼嗎? –

回答

0

如果你有StringBuffer的對象,那麼你需要迭代它並替換字符:

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

或將其轉換成字符串然後如下替換:

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

在這裏使用正則表達式會更可讀 – radai

+0

@radai是的,它會.. – Kick

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+", "-")); 
0

做這樣

StringBuffer tokenstr=new StringBuffer(); 
tokenstr.append("technician education systems of the Cabinet has approved the following".replace(" ", "-")); 
System.out.print(tokenstr); 
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); 
0

你需要編寫自定義replaceAll方法。你需要找到src字符串索引並用目標字符串替換那些字符串子字符串。

請找到Jon Skeet

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,"-"); 
} 
0

/您可以使用以下方法通您的字符串參數並將結果作爲字符串空格替換爲連字符/

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