簡體   English   中英

Java中帶分隔符的字符串

[英]SPlit string in java with delimiter

我的字符串是Spiderman|Batman|Superman我想分割字符串,使輸出看起來像Spiderman Batman Superman我嘗試了以下方法:

String actors = "Spiderman|Batman|Superman";
String [] temp;
String delimiter = "|";

temp = actors.split(delimiter);
for (int i =0; i<temp.length; i++)
           System.out.print(temp[i].replaceAll("\\|", " "));

我該如何做得更好? 輸出沒有意義。 謝謝您的期待。 輸出仍然與輸入相同。 編譯之后,它向我顯示了這一點:

Spiderman|Batman|Superman

就像split方法從未開始過。

第二個問題

請看這張照片。 如果我使用100k字符串,則如下所示: eclipse控制台的屏幕截圖

請在for循環后查看我的代碼中的注釋。 我的分割字符串有效,但輸出奇怪。 (請看截圖),我認為這是由“打印”引起的,或者沒有足夠的空間來表示將近300 k的字符串。 我用eclipse連接了數據庫項目。 在postgres中,我導入了一個.csv文件,其中包含有關將近30萬部電影的一些信息。 例如演員導演,年份,等級等。這是我的問題:

這是我的Java代碼

package dbs;
import java.sql.*;

 public class Fertigevariante {

public static void main(String[] args) {
    try {
    Class.forName("org.postgresql.Driver");
    String url= "jdbc:postgresql://localhost:5432/postgres?user=postgres&password=password";
    Connection conn = DriverManager.getConnection(url);


    Statement st= conn.createStatement();
    ResultSet rs= st.executeQuery("SELECT * FROM kinofilme");
    while (rs.next()){
        String imdib= rs.getString("imdib");
        String rating = rs.getString("rating");
        int votes = rs.getInt("votes");
        String runtime = rs.getString("runtime");
        String name = rs.getString("name");
        String directors = rs.getString("directors");
        String actors = rs.getString("actors");

        String [] temp;
        String delimiter ="|";

        temp = actors.split(delimiter);
        for(int j=0 ; j < temp.length; j++)
                System.out.print( temp[j].replaceAll("\\|", " ")); // here is the output problem, look at the screenshot I uploaded here.


        int year = rs.getInt("year");
   //   System.out.println(imdib + "\t" + name + "\t" + year + "\t" + votes + "\t" + directors + "\t" + actors);

    }
    rs.close();
    st.close();




    conn.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }



}
 }

當您拆分然后使用print您將獲得:“ SpidermanBatmanSuperman”

由於要在兩者之間留一個空格,因此可以將最后一行替換為:

System.out.print(temp[i] + " ");

但是,只需替換子字符串“ |”,您甚至可以做得更好 帶有空格:“”

System.out.print("Spiderman|Batman|Superman".replaceAll("\\|", " "));

在這兩種情況下,輸出均為:

Spiderman Batman Superman

重要事項

拆分/替換時| 您應該轉義它,因為它是一個具有正則表達式含義的特殊字符!

quote split的正則表達式參數

temp = actors.split(Pattern.quote(delimiter));

split接受正則表達式作為參數- | 是正則表達式中的特殊字符。 嘗試"\\\\|" 作為分隔符,或使用Pattern.quote(delimiter)

暫無
暫無

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

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