我的方法需要檢查給定的字符串是否等於定義的模板,實際上它不會按預期產生輸出。模板輸入字符串
Inputstring:18122016 with template「...」會正確地返回「二○一六年十二月一十八日」
Inputstring:15:00模板「:」將返回「15:500」,這是不對的,預期爲15:00
也許有人比我更清晰的解決方案?
這是我的測試用例:
@Test
public void testDoCandidateWithTextTemplate() {
ArrayList<String> tWords = new ArrayList<>();
tWords.add(":");
String result = VORecognitionResultsImpl.doCandidateWithTextTemplate("1500", tWords, " :");
assertEquals("15:00", result);
result = VORecognitionResultsImpl.doCandidateWithTextTemplate("15:00", tWords, " :");
assertEquals("15:00", result);
result = VORecognitionResultsImpl.doCandidateWithTextTemplate("18122016", tWords, " . .");
assertEquals("18.12.2016", result);
result = VORecognitionResultsImpl.doCandidateWithTextTemplate("1437", tWords, " ,");
assertEquals("14,37", result);
}
這裏是方法
public static String doCandidateWithTextTemplate(String tmpTextCandidate,
ArrayList<String> tWords,
String textTemplate)
{
if(textTemplate == null) return tmpTextCandidate;
if(textTemplate.length() == 0) return tmpTextCandidate;
StringBuffer outText = new StringBuffer();
int currentIndex = 0;
boolean isInserted = false;
for(int i = 0; i < textTemplate.length();i++){
currentIndex = i;
if (textTemplate.charAt(i) == ' '){
if (!isInserted){
outText.append(tmpTextCandidate.charAt(i));
}
else{
outText.append(tmpTextCandidate.charAt(i-1));
isInserted = false;
}
}
else{
if (textTemplate.charAt(i) != tmpTextCandidate.charAt(i)){
outText.append(textTemplate.charAt(i));
isInserted = true;
}
}
}
if (currentIndex < tmpTextCandidate.length()-1){
outText.append(tmpTextCandidate.substring(currentIndex-1, tmpTextCandidate.length()));
}
return outText.toString();
}
如果輸入爲「18123016」輸出爲18.13.3016,那麼在您的索引計算中存在錯誤時,您的代碼也可能會中斷。你只是不能做索引1,它必須是持久的,我的建議是使用兩個索引我和j,這將使您的代碼更具可讀性並且易於糾正 –