簡體   English   中英

使用公共分隔符獲取字符串的第 n 個 substring

[英]Get nth substring of string with common delimiter

我在 groovy web 控制台中工作,並希望獲得由 / 分隔的第三個也是最后一個 substring。 我已經能夠使用 lastIndexOf() 獲得最后一個 substring 並且可以根據需要獲得第一個,但是對於我的一生來說,我無法找到任何快速簡單的方法來獲得第二次和第三次出現的索引/ 以便我可以提取第三個 substring。 從下面的代碼中,我想要的 output 將是:

生產
蘋果

在我的示例中,我目前正在打印 pathDelim 只是為了進行健全性檢查,所以請忽略它為什么存在。 抱歉,如果這是一個簡單的問題,但我是 groovy 的新手,主要來自 SQL 背景,這將是一項簡單快捷的任務。 提前致謝!

productPath = "Store/Grocery/Produce/Apples";

int pathDelim = productPath.lastIndexOf('/');
itemName = (productPath.substring(pathDelim + 1));

println pathDelim;
println itemName;

您是否考慮過僅拆分字符串?

​productPath.split('/')[2, 3].each {
    println it
}

打印您想要的 output:

Produce
Apples

如果你需要你可以做的所有索引

​productPath.findIndexValues { it == '/' }

哪個返回

[5, 13, 21]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM