在輸入處我有一些字符串:「今天下雪知道」,在這裏我有3個單詞,所以我必須解析它們是這樣的:每個角色我必須與所有其他角色比較,並且總和這些詞有多少個相同的字符,比如「o」字母的例子是2(來自「今天」和「下雪」)或者「w」字母將是2(來自「知道」和「下雪」)。之後,我必須用字母數字(轉換爲字符格式)替換這些字符。結果應該是「13111 133211 1332」。解析字符串並替換字母Java
我做了什麼?
首先我一卷錄音帶,一些單詞和
public void inputStringsForThreads() {
boolean flag;
do {
// will invite to input
stringToParse = Input.value();
try {
flag = true;
// in case that found nothing , space , number and other special character , throws an exception
if (stringToParse.equals("") | stringToParse.startsWith(" ") | stringToParse.matches(".*[0-9].*") | stringToParse.matches(".*[~`[email protected]#$%^&*()-+={};:',.<>?/'_].*"))
throw new MyStringException(stringToParse);
else analizeString(stringToParse);
}
catch (MyStringException exception) {
stringToParse = null;
flag = false;
exception.AnalizeException();
}
}
while (!flag);
}
我消除單詞之間的空格,並從這些話讓只是一個
static void analizeString (String someString) {
// + sign treat many spaces as one
String delimitator = " +";
// words is a String Array
words = someString.split(delimitator);
// temp is a string , will contain a single word
temp = someString.replaceAll("[^a-z^A-Z]","");
System.out.println("=============== Words are : ===============");
for (int i=0;i<words.length;i++)
System.out.println((i+1)+")"+words[i]);
}
所以我儘量對每一個字部分的每一個字比較(被分成字母)與所有字母的所有字母,但我不知道如何計算同一個字母的數字,並在每個字母的正確數字替換字母后?有任何想法嗎 ?
// this will containt characters for every word in part
char[] motot = words[id].toCharArray();
// this will containt all characters from all words
char[] notot = temp.toCharArray();
for (int i =0;i<words[i].length();i++)
for (int j=0;j<temp.length ;j++)
{
if (i == j) {
System.out.println("Same word");
}
else if (motot[i] == notot[j]) {
System.out.println("Found equal :"+lol[i]+" "+lol1[j]);
}}
嘗試'HashMap <字符,整數>'。 – Kevin
這功課嗎? – Perception
大寫/小寫字母怎麼樣(它們是否被認爲是用於計數的相同字符)? –