2009-07-25 437 views
92

我正在使用字符串拆分方法,並且我想要最後一個元素。 數組的大小可以更改。Java:獲取拆分後的最後一個元素

例子:

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? 

我不知道該數組的大小在運行時:(

+1

取而代之,您可以使用substring和indexof。 – 2014-08-27 02:47:03

+0

@SurendarKannan最頂尖的答案有一個例子,用lastIndexOf。 – 2014-08-27 03:59:34

回答

137

將數組保存在本地變量中,並使用數組的length字段查找其長度。 d:

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

請注意,在輸入字符串爲空的情況下,第二條語句將拋出「索引超出範圍」異常。 – 2009-07-26 01:23:43

+3

沒有它不會,你分裂一個空字符串它將返回一個數組包含一個元素,這是一個空字符串本身。 – Panthro 2017-07-27 18:45:32

3

你的意思是你不知道在編譯時數組的大小?在運行時,可以通過lastone.lengthlastwo.length的值找到它們。

188

或者你可以使用一個簡單而通用,輔助方法,這樣使用lastIndexOf()方法對字符串

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

我認爲這個解決方案佔用更少的資源。 – ufk 2010-05-26 15:32:44

21

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

你可以重寫:

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

爲:

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

因爲他是問做這一切在同一行中採用分體式所以我的建議是:

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

我總是避免定義爲盡我所能新的變量,我覺得這是一個非常好的實踐

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

現在lastString具有價值"directory"

6

隨着Guava

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

SplitterIterables

12

可以使用StringUtils類中的Apache Commons:中

StringUtils.substringAfterLast(one, "-"); 
0

我猜你要行做到這一點的我。這是可能的(有點雜耍雖然= ^)

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

tadaa,一條線 - 的(空間負空間),而不是唯一的 - >你想(如果拆分的結果「」「 - 」(減號)你會鬆動分區之前的煩人的空間= ^)所以「GünnewigUebachs」,而不是「GünnewigUebachs」(用空格作爲第一個字符)

好的額外 - >不需要額外的JAR文件這樣你可以保持你的應用程序輕量級。

0

您也可以使用java.util.ArrayDeque

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

在java中8

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

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


通過使用的Java.lang.String

// 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); 

split()Java SE 1.4lastIndexOf() & substring()方法。將提供的文本拆分成數組。

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

爪哇8順序從陣列有序stream

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); 

阿帕奇共享郎jar«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 Core Libraries。 «com.google.common.base。分配器

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); 

Scripting for the Java Platform«運行JavaScript於JVM犀牛/犀牛

  • Rhino«Rhino是一個開源的JavaScript實現完全用Java編寫。它通常嵌入到Java應用程序中以向最終用戶提供腳本。它作爲默認的Java腳本引擎嵌入在J2SE 6中。

  • Nashorn是由Oracle以Java編程語言開發的JavaScript引擎。它是基於達芬奇機和已經發布的Java 8

的Java腳本Programmer's Guide

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); } 
相關問題