Java: 分割后获取最后一个元素

我正在使用 String 分割方法,并且我希望拥有最后一个元素。 Array 的大小可以更改。

例如:

String one = "Düsseldorf - Zentrum - Günnewig Uebachs"
String two = "Düsseldorf - Madison"

我想分割上面的字符串,得到最后一个项目:

lastone = one.split("-")[here the last item] // <- how?
lasttwo = two.split("-")[here the last item] // <- how?

我不知道数组在运行时的大小: (

301268 次浏览

将数组保存在局部变量中,并使用数组的 length字段查找其长度。减去1,说明它是从0开始的:

String[] bits = one.split("-");
String lastOne = bits[bits.length-1];

注意: 如果原始字符串只由分隔符组成,例如 "-""---",那么 bits.length将为0,这将抛出 ArrayIndexOutOfBoundsException 异常。例子: https://onlinegdb.com/r1M-TJkZ8

你的意思是你不知道数组在编译时的大小?在运行时,可以通过值 lastone.lengthlastwo.length找到它们。

可以对 String 使用 lastIndexOf()方法

String last = string.substring(string.lastIndexOf('-') + 1);

使用如下简单但通用的 helper 方法:

public static <T> T last(T[] array) {
return array[array.length - 1];
}

你可以重写:

lastone = one.split("-")[..];

作为:

lastone = last(one.split("-"));

因为他要求在同一行中使用 Split,所以我建议这样做:

lastone = one.split("-")[(one.split("-")).length -1]

我总是尽量避免定义新的变量,我发现这是一个很好的实践

String str = "www.anywebsite.com/folder/subfolder/directory";
int index = str.lastIndexOf('/');
String lastString = str.substring(index +1);

现在 lastString的值为 "directory"

番石榴:

final Splitter splitter = Splitter.on("-").trimResults();
assertEquals("Günnewig Uebachs", Iterables.getLast(splitter.split(one)));
assertEquals("Madison", Iterables.getLast(splitter.split(two)));

Splitter ,< a href = “ http://docs.guava-library aries.googlecode.com/git/javadoc/com/google/common/Collection/Iterables.html”rel = “ noReferrer”> Iterables

您可以在 Apache Commons 中使用 StringUtils类:

StringUtils.substringAfterLast(one, "-");

我猜你想在 i 行做这件事,这是可能的(有点杂耍虽然 = ^)

new StringBuilder(new StringBuilder("Düsseldorf - Zentrum - Günnewig Uebachs").reverse().toString().split(" - ")[0]).reverse()

Tadaa,一行-> 你想要的结果(如果你分割为“-”(空间减去空间)而不仅仅是“-”(减去空间) ,你会在分割之前松开恼人的空间 too = ^) ,所以“ Günnewig Uebachs”而不是“ Günnewig Uebachs”(以空间作为第一个字符)

不错的额外-> 不需要在 lib 文件夹中添加额外的 JAR 文件,这样您就可以保持应用程序的轻量级。

你也可以使用 java.util.ArrayDeque

String last = new ArrayDeque<>(Arrays.asList("1-2".split("-"))).getLast();

在爪哇8

String lastItem = Stream.of(str.split("-")).reduce((first,last)->last).get();

聚集了所有可能的方式在一起! !


采用 Java.lang.StringlastIndexOf()substring()方法

// int firstIndex = str.indexOf( separator );
int lastIndexOf = str.lastIndexOf( separator );
String begningPortion = str.substring( 0, lastIndexOf );
String endPortion = str.substring( lastIndexOf + 1 );
System.out.println("First Portion : " + begningPortion );
System.out.println("Last  Portion : " + endPortion );

将提供的文本拆分为数组。

String[] split = str.split( Pattern.quote( separator ) );
String lastOne = split[split.length-1];
System.out.println("Split Array : "+ lastOne);

Java8从数组中顺序排列的 溪流

String firstItem = Stream.of( split )
.reduce( (first,last) -> first ).get();
String lastItem = Stream.of( split )
.reduce( (first,last) -> last ).get();
System.out.println("First Item : "+ firstItem);
System.out.println("Last  Item : "+ lastItem);

Apache Commons Lang~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~org.apache.commons.lang3.StringUtils

String afterLast = StringUtils.substringAfterLast(str, separator);
System.out.println("StringUtils AfterLast : "+ afterLast);


String beforeLast = StringUtils.substringBeforeLast(str, separator);
System.out.println("StringUtils BeforeLast : "+ beforeLast);


String open = "[", close = "]";
String[] groups = StringUtils.substringsBetween("Yash[777]Sam[7]", open, close);
System.out.println("String that is nested in between two Strings "+ groups[0]);

Guava : 用于 Java 的 Google 核心库“ com.Google.common.base. Splitter

Splitter splitter = Splitter.on( separator ).trimResults();
Iterable<String> iterable = splitter.split( str );
String first_Iterable = Iterables.getFirst(iterable, "");
String last_Iterable = Iterables.getLast( iterable );
System.out.println(" Guava FirstElement : "+ first_Iterable);
System.out.println(" Guava LastElement  : "+ last_Iterable);

Java 平台脚本 “用 Rhino/Nashorn 在 JVM 上运行 Javascript

  • Rhino “ Rhino 是完全用 Java 编写的 JavaScript 的开源实现。它通常嵌入到 Java 应用程序中,为最终用户提供脚本。它作为默认的 Java 脚本引擎嵌入在 J2SE6中。

  • Nashorn 是 Oracle 用 Java 编程语言开发的 JavaScript 引擎。它基于达芬奇机器,并已与 Java8一起发布。

Java 脚本 程序员指南

public class SplitOperations {
public static void main(String[] args) {
String str = "my.file.png.jpeg", separator = ".";
javascript_Split(str, separator);
}
public static void javascript_Split( String str, String separator ) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");


// Script Variables « expose java objects as variable to script.
engine.put("strJS", str);


// JavaScript code from file
File file = new File("E:/StringSplit.js");
// expose File object as variable to script
engine.put("file", file);


try {
engine.eval("print('Script Variables « expose java objects as variable to script.', strJS)");


// javax.script.Invocable is an optional interface.
Invocable inv = (Invocable) engine;


// JavaScript code in a String
String functions = "function functionName( functionParam ) { print('Hello, ' + functionParam); }";
engine.eval(functions);
// invoke the global function named "functionName"
inv.invokeFunction("functionName", "function Param value!!" );


// evaluate a script string. The script accesses "file" variable and calls method on it
engine.eval("print(file.getAbsolutePath())");
// evaluate JavaScript code from given file - specified by first argument
engine.eval( new java.io.FileReader( file ) );


String[] typedArray = (String[]) inv.invokeFunction("splitasJavaArray", str );
System.out.println("File : Function returns an array : "+ typedArray[1] );


ScriptObjectMirror scriptObject = (ScriptObjectMirror) inv.invokeFunction("splitasJavaScriptArray", str, separator );
System.out.println("File : Function return script obj : "+ convert( scriptObject ) );


Object eval = engine.eval("(function() {return ['a', 'b'];})()");
Object result = convert(eval);
System.out.println("Result: {}"+ result);


// JavaScript code in a String. This code defines a script object 'obj' with one method called 'hello'.
String objectFunction = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
engine.eval(objectFunction);
// get script object on which we want to call the method
Object object = engine.get("obj");
inv.invokeMethod(object, "hello", "Yash !!" );


Object fileObjectFunction = engine.get("objfile");
inv.invokeMethod(fileObjectFunction, "hello", "Yashwanth !!" );
} catch (ScriptException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}


public static Object convert(final Object obj) {
System.out.println("\tJAVASCRIPT OBJECT: {}"+ obj.getClass());
if (obj instanceof Bindings) {
try {
final Class<?> cls = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror");
System.out.println("\tNashorn detected");
if (cls.isAssignableFrom(obj.getClass())) {
final Method isArray = cls.getMethod("isArray");
final Object result = isArray.invoke(obj);
if (result != null && result.equals(true)) {
final Method values = cls.getMethod("values");
final Object vals = values.invoke(obj);
System.err.println( vals );
if (vals instanceof Collection<?>) {
final Collection<?> coll = (Collection<?>) vals;
Object[] array = coll.toArray(new Object[0]);
return array;
}
}
}
} catch (ClassNotFoundException | NoSuchMethodException | SecurityException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
}
}
if (obj instanceof List<?>) {
final List<?> list = (List<?>) obj;
Object[] array = list.toArray(new Object[0]);
return array;
}
return obj;
}
}

JavaScript 文件“ StringSplit.js

// var str = 'angular.1.5.6.js', separator = ".";
function splitasJavaArray( str ) {
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
print('Regex Split : ', result);
var JavaArray = Java.to(result, "java.lang.String[]");
return JavaArray;
// return result;
}
function splitasJavaScriptArray( str, separator) {
var arr = str.split( separator ); // Split the string using dot as separator
var lastVal = arr.pop(); // remove from the end
var firstVal = arr.shift(); // remove from the front
var middleVal = arr.join( separator ); // Re-join the remaining substrings


var mainArr = new Array();
mainArr.push( firstVal ); // add to the end
mainArr.push( middleVal );
mainArr.push( lastVal );


return mainArr;
}


var objfile = new Object();
objfile.hello = function(name) { print('File : Hello, ' + name); }