2009-07-25 45 views
92

Tôi đang sử dụng phương thức tách chuỗi và tôi muốn có phần tử cuối cùng. Kích thước của Array có thể thay đổi.Java: Lấy phần tử cuối cùng sau khi tách

Ví dụ:

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

Tôi muốn chia Strings trên và nhận được mục cuối cùng:

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

Tôi không biết các kích thước của mảng tại thời gian chạy :(

+1

Thay vì điều này, bạn có thể sử dụng chuỗi con và indexof. –

+0

@SurendarKannan Câu trả lời bình chọn hàng đầu có ví dụ về điều đó, với lastIndexOf. –

Trả lời

137

Lưu mảng trong biến cục bộ và sử dụng trường length của mảng để tìm độ dài của nó. Trừ một giá trị cho tài khoản là 0-base d:

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

Chỉ cần lưu ý rằng trong trường hợp chuỗi đầu vào trống, câu lệnh thứ hai sẽ ném một ngoại lệ "index out of bounds". –

+3

không có vấn đề gì, bạn chia một chuỗi rỗng nó sẽ trả về một mảng chứa một phần tử là chính chuỗi rỗng. – Panthro

3

Bạn có nghĩa là bạn không biết kích thước của mảng tại thời gian biên dịch? Vào thời gian chạy, chúng có thể được tìm thấy theo giá trị lastone.lengthlastwo.length.

188

Hoặc bạn có thể sử dụng lastIndexOf() phương pháp trên Chuỗi

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

tôi nghĩ rằng giải pháp này mất ít tài nguyên hơn. – ufk

+0

Sẽ không ném một 'IndexOutOfBoundsException' nếu' chuỗi' không chứa ''-''? –

+4

Không, @JaredBeck, không. Nhưng nó trả về toàn bộ chuỗi, có thể hoặc không muốn bạn muốn. Có thể tốt hơn để kiểm tra xem ký tự bạn đang tách có tồn tại trong chuỗi đầu tiên không. –

21

sử dụng một phương pháp helper đơn giản, nhưng chung chung như thế này:

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

bạn có thể viết lại:

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

như :

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

Một điều bạn nên làm là bảo vệ phương thức last() chống lại các mảng trống hoặc bạn có thể nhận được IndexOutOfBoundsException. –

+0

@dotsid, Mặt khác nó có thể là tốt hơn để ném một ArrayIndexOutOfBoundsException hơn là trả về null ở đây, vì bạn sẽ bắt gặp lỗi khi nó xảy ra thay vì khi nó gây ra vấn đề. –

+1

@dotsid, tôi sẽ để lại trách nhiệm này cho người gọi, ẩn các ngoại lệ thời gian chạy là nguy hiểm – dfa

5

Kể từ khi ông được hỏi để làm tất cả trong cùng một dòng sử dụng split vì vậy tôi đề nghị này:

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

Tôi luôn tránh xác định các biến mới như xa như tôi có thể, và tôi thấy nó rất tốt thực hành

+0

Nhưng điều đó sẽ ném một 'IndexOutOfBoundsException' nếu chuỗi không chứa' -' – Stoinov

+0

@Stoinov, Thực ra nó sẽ không. bạn có thể kiểm tra nó! ;) – azerafati

+0

bạn có thể kiểm tra nó ở đây !! http://ideone.com/or83Mg – azerafati

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

Bây giờ lastString có giá trị "directory"

6

với Guava:

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

Splitter, Iterables

12

Bạn có thể sử dụng lớp StringUtils trong Apache Commons:

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

Tôi đoán bạn muốn làm điều này trong i dòng.Có thể (một chút tung hứng dù = ^)

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

tadaa, một dòng -> kết quả bạn muốn (nếu bạn chia trên "-" (không gian trừ gian) thay vì chỉ "-" (trừ) bạn sẽ mất không gian gây phiền nhiễu trước phân vùng quá = ^) để "Günnewig Uebachs" thay vì "Günnewig Uebachs" (với khoảng trắng là ký tự đầu tiên)

Đẹp bổ sung -> không cần thêm tệp JAR trong lib để bạn có thể giữ cho trọng lượng nhẹ của ứng dụng.

0

Ngoài ra bạn có thể sử dụng java.util.ArrayDeque

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

Trong java 8

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

Tập hợp tất cả các cách có thể cùng nhau !!


Bằng cách sử dụng lastIndexOf() & substring() phương pháp 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.4. Tách văn bản được cung cấp thành một mảng.

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

Java 8 tuần tự ra lệnh stream từ một mảng.

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 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: Thư viện lõi của Google dành cho Java. «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); 

Scripting for the Java Platform «Run Javascript trên JVM với Rhino/Nashorn

  • Rhino« Rhino là một thực hiện mã nguồn mở của JavaScript được viết hoàn toàn bằng Java. Nó thường được nhúng vào các ứng dụng Java để cung cấp kịch bản cho người dùng cuối. Nó được nhúng trong J2SE 6 làm công cụ tạo mã Java mặc định.

  • Nashorn là một công cụ JavaScript được phát triển bằng ngôn ngữ lập trình Java của Oracle. Nó được dựa trên Da Vinci Máy và đã được phát hành với Java 8.

Java Scripting 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 tập tin «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); } 
Các vấn đề liên quan