[英]Java extracting specific characters from random string
我是新手,我有一個隨機給我一個字符串的程序。
我的任務是從此字符串中提取並顯示特定字符。
例如:
String s = "condor:4,2:d\nocelot:12,12:h\nvocabulary:12,12:g\nwilderness:1,3:b";
顯示:
condor, ocelot, vocabulary, wilderness
我只能使用類字符串和System.No標記程序,沒有表[],沒有ArrayList()。
使用以下代碼解決您的問題:
在for循環中,逐個字符地對char進行迭代,並檢查字符ascii代碼是否在字母范圍內;在此條件塊中,如果答案為true,則將字符添加到temp中,后者的first首先為空,如果answer為false,而temp不是為空並且不僅僅是字母打印溫度。 最后一個if字符串是否由循環的單詞的最后一個字符完成
int a;
String temp = "";
String nodes = "condor:4,2:d\nocelot:12,12:h\nvocabulary:12,12:g\nwilderness:1,3:b";
for (int i = 0; i < nodes.length(); i++) {
a = (int) nodes.charAt(i);
if ((a >= 97 && a <= 122) || (a >= 65 && a <= 90)) {
temp = temp + nodes.charAt(i);
} else if (temp != "" && temp.length() != 1) {
System.out.println(temp);
temp = "";
}else if(temp != "" && temp.length() == 1){
temp = "";
}
}
if (temp != "" && temp.length() != 1)
System.out.println(temp);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.