我有大文本文件,每个文件都包含单词和数字字符串。 我需要将这些数字增加一个固定值,并将它们写回到之前在该字符串中的位置。
我想要添加的值取决于数字前面的单词,并且每个没有这些关键字的数字都必须不。
我的方法是分隔空格字符,检查单词并在我找到关键字后处理数字。但是,这使我要求在单词和数字之间有空格字符,这是不确定的。
此外,当从拆分数组重新组装字符串时,这可能会破坏之前的布局。
可以是一个例子 “马克相当大,189厘米,出生于1978年。但是,他只有一个关于解析的问题,他真的无法理解。”
大,高度应该增加5,年后,数字减去19。数字1应保持不变,因为只是不是关键字。
我可以同时使用java或python,因为这些是我所知道的语言。
答案 0 :(得分:1)
我想我得到了一些东西:
public class Start {
public static void main(String[] args){
//Test String
String s = "not4inc6desc3inc14";
StringBuffer sb = new StringBuffer(s);
//keep track where new word begins
int newWord = 0;
for(int i = 0; i < sb.length(); i++){
//chekc if the new Character is a number
if(checkNumber(sb.substring(i, i+1))){
//if the old word ends with "inc"
//maybe try out .contains()
if(sb.substring(newWord, i).endsWith("inc")){
//replace number
StringBuffer temp = new StringBuffer();
int j = 0;
//get full number
for(j = i; j < sb.length() && checkNumber(sb.substring(j, j+1)); j++){
temp.append(sb.substring(j, j+1));
}
//modify number
int number = Integer.parseInt(temp.toString()) + 1;
//replace number
sb.replace(i, i + temp.length(), Integer.toString(number));
//number no longer needs to be checked for being a word
i=j;
}
}
}
//print test String
System.out.println(sb.toString());
}
// Check if String is numeric
private static boolean checkNumber(String s){
try{
Integer.parseInt(s);
}catch(NumberFormatException e ){
return false;
}
return true;
}
}
对不起,我有点难以理解......随意问......