我已經使用這個代碼嘗試了這一點:如何計算Java中每個字符串中的字母?
String st="Hello world have a nice day";
String arr=st.Split(" ");
for (int i=0; i < arr.length; i++) {
???
}
但它不工作。
我希望它的輸出是這樣的:
Hello=5
World=5
have=4
a=1
nice=4
day=3
有誰知道正確的代碼,請?
我已經使用這個代碼嘗試了這一點:如何計算Java中每個字符串中的字母?
String st="Hello world have a nice day";
String arr=st.Split(" ");
for (int i=0; i < arr.length; i++) {
???
}
但它不工作。
我希望它的輸出是這樣的:
Hello=5
World=5
have=4
a=1
nice=4
day=3
有誰知道正確的代碼,請?
您可以使用這樣的事情:
String[] words = yourString.split(" ");
for (String word : words) {
System.out.println(word + " length is: " + word.length());
}
使用for循環的增強,並打印出來的字和它的長度。
foreach(String w : st.split()) {
System.out.println(w + ": " + w.length());
}
word.length()
返回字符串的長度。
但是,split()
方法只是將空格分開,將所有內容留在生成的分割中。通過我的一切,我的意思是標點符號,製表符,換行符等,所有這些將被計算在長度。因此,不要只是在做word.length()
,您可能想要做類似的事情:
word.replaceAll("\p{Punct}", "").trim().length()
。
replaceAll("\p{Punct}", "")
將刪除 字符串中所有標點符號。
trim()
刪除所有前導和尾隨空格。
因此,例如,一個句子:
只見鬼火\ n
(\n
意味着行字符,結束這例如,如果你從文件中讀取字符串,你可能會得到)。
的判決將拆分:
"I"
"saw"
"a"
"will-o'-the-wisp.\n"
最後一個字符串
鬼火\ n
有18個字符,但是這更多。而不是單詞中的字符數。該replaceAll()
方法後,該字符串看起來像:
鬼火\ n
和trim()
方法之後,該字符串將是這樣的:
鬼火
其中長度爲12,單詞的長度。