【发布时间】:2012-01-22 08:57:06
【问题描述】:
在输入时我有一些字符串:“今天下雪知道”,这里我有 3 个单词,所以我必须这样解析它们:我必须将每个字符与所有其他字符进行比较,并总结这些字符有多少相同的字符单词 have ,例如“o”字母将是 2(来自“today”和“snowing”)或“w”字母将是 2(来自“know”和“snowing”)。之后,我必须用字母的数字(转换为字符格式)替换这些字符。结果应该是“13111 133211 1332”。
我做了什么?
首先我把一些单词录下来
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(".*[~`!@#$%^&*()-+={};:',.<>?/'_].*"))
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<Character,Integer>。 -
大写/小写字母呢(出于计数目的,它们是否被认为是相同的字符)?