您好我正在寻找一个解决方案,它将从给定索引的字符串返回一个子字符串。为了避免当前使用if和else check的索引绑定异常。这是一个更好的方法(功能)。
String ordenObtenida = "{\"status\":\"ok\",\"tipo\":\"" + tipo + "\",\"ordenes\":\[;
while (rs.next()) {
hasRow = true;
if (rs.getString("razon") != null) {
razon = rs.getString("razon").replaceAll("\"", "").trim();
}
ordenObtenida += "{\"numero\":\"" + rs.getInt("numero") + "\",\"fecha\":\"" + rs.getDate("fecha") + "\",\"proveedor\":\"" + rs.getInt("proveedor") + "\","
+ "\"codigo\":\"" + rs.getInt("codigo") + "\",\"orden\":\"" + rs.getInt("orden") + "\",\"fepago\":\"" + rs.getDate("fepago") + "\",\"marca\":\"" + rs.getInt("marca") + "\","
+ "\"razon\":\"" + razon + "\",\"importe\":\"" + rs.getFloat("importe") + "\"},";
}
ordenObtenida = ordenObtenida.substring(0, ordenObtenida.length() - 1) + "]\"}";
答案 0 :(得分:4)
如果索引超出范围,不确定您希望函数做什么,但slice
可能符合您的需求:
input.slice(start, end)
一些例子:
scala> "hello".slice(1, 2)
res6: String = e
scala> "hello".slice(1, 30)
res7: String = ello
scala> "hello".slice(7, 8)
res8: String = ""
scala> "hello".slice(0, 5)
res9: String = hello
答案 1 :(得分:3)
Try
是这样做的一种方式。另一种方法是仅当长度大于使用Option[String]
的结束时才应用子字符串。
无效的结束索引
scala> val start = 1
start: Int = 1
scala> val end = 1000
end: Int = 1000
scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res9: Option[String] = None
有效的结束索引
scala> val end = 6
end: Int = 6
scala> Option("urayagppd").filter(_.length > end).map(_.substring(start, end))
res10: Option[String] = Some(rayag)
此外,您可以将filter
和map
合并到.collect
,如下所示
scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res14: Option[String] = Some(rayag)
scala> val end = 1000
end: Int = 1000
scala> Option("urayagppd").collect { case x if x.length > end => x.substring(start, end) }
res15: Option[String] = None