繁体   English   中英

如何在Java中拆分字符串数组

[英]how to split an array of strings in java

我有一个字符串类型的数组,它保存来自数据库的列,该数据库保存日期和时间的值为2014-11-12 16:08:48。 现在,我必须拆分数组,以便仅检索时间值,即16:08:48。 如何在数组上应用拆分?

提前致谢。

我通过其检索列值的代码是

 public String[] getChartTime() throws SQLException { List < String > timeStr = new ArrayList < String > (); String atime[] = null; getConnection(); try { con = getConnection(); String sql = "exec vcs_gauge @gauge_name=?,@first_rec_time=?,@last_rec_time=?"; DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("date is " + df.format(currentDate)); clstmt = con.prepareCall(sql); clstmt.setString(1, "vs3_bag"); clstmt.setString(2, "2014-09-01 10:00:00"); clstmt.setString(3, "2014-09-01 11:00:00"); clstmt.execute(); rs = clstmt.getResultSet(); while (rs.next()) { // Just get the value of the column, and add it to the list timeStr.add(rs.getString(1)); } } catch (Exception e) { System.out.println("\\nException in Bean in getDbTable(String code):" + e); } finally { closeConnection(); } // I would return the list here, but let's convert it to an array atime = timeStr.toArray(new String[timeStr.size()]); return atime; } 

现在,我想分割timestr数组,以便只获得时间,而没有日期。

您可以使用String.split()方法(以space作为分隔符)。 您可以使用下面的代码来做到这一点:

String[] atime = new String[3600];
Iterator<String> it = timeStr.iterator();
int i = 0;
while(it.hasNext()) {
    atime[i] = it.next().toString().split("\\s")[1]; /* stores each time in each index of atime */
    i++;
}

完成此操作后,结果将在String数组atime[]

您可以使用以下代码轻松完成此操作:

// Just get the value of the column, and add it to the list
timeStr.add(rs.getString(1).split(" ")[1]);

我通过使用substring解决了我的问题。代码是

  while (rs.next()) { // Just get the value of the column, and add it to the list timeStr.add(rs.getString(1).substring(11, 16)); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM