如何从涉及其他字符的字符串中获取int?

问题描述:

我正在写一个程序,我想遍历一个文档中的某些属性,看起来像这样的ID:如何从涉及其他字符的字符串中获取int?

"id": "competitor:2672" 

我想根据我从一个excel文件中读取的数据进行迭代。唯一的问题是,在所述excel文件中,ID仅以“竞争者ID”列给出为

2672 

我无法将给定的字符串解析为整数。什么是比较两个ID

使用Apache POI的最好和最干净的方式,我想这样做

String COLUMN_ID = "G" // Column letter in which the IDs are stored 
Document home = competitors.get(0); 
Document away = competitors.get(1); 
String homeIDString = home.get("id").toString(); 
int homeID = //how to get this from the upper string? 
String awayIDString = away.get("id").toString(); 
int awayID = //how to get this from the upper string? 
XSSFWorkbook workbook = new XSSFWorkbook(inputStream); 
XSSFSheet sheet = workbook.getSheetAt(0); 
for (int row=0; <something>; row++) { 
    XSSFCell cell = sheet.getRow(row).getCell(CellReference.convertColStringToIndex(COLUMN_ID)); 
    if (cell.getCellTypeEnum().equals(NUMERIC)) int cellValue = (int) cell.getNumericValue(); 
    if (cellValue == homeID) { do something } 
    else if (cellValue == awayID) { do something } 
} 
+1

之前使用子只删除competitor:“*我无法分析给定的字符串到整数*。” - 为什么不呢?我想你可以检查id字符串是否以excel中的数字结尾,但我不明白是什么阻止了你从字符串中提取数字并将其作为数字进行比较。 – azurefrog

+0

我在编程方面不是很有经验,但据我的经验,这会给我一个** NumberFormatException **。或者我错了? –

目前你得到一个NumberFormatException因为你想你的String转换成int然后再与另一个int比较。

@azurefrog说的是,你可以尝试,而不是你的int转换为String(反过来),它会没事的。

strVariable.endsWith(String.valueOf(intVariable))

然而,这具有"id": "competitor:2672"72将返回true太多的问题。


一个更好的办法是将2672为int

String myInput = "competitor:2672";  // "competitor:2672" 
myInput = myInput.substring(11);   // "2672" 
int myValue = Integer.parseInt(myInput); // 2672