[英]Splitting string into two separate
好吧,我的意思是,我創建了一個String類型的變量,然后在加載文件時,我必須將內容保存在一個變量中,在這種情況下,該變量是“ TextFromFile”,加載后,我想將其分為兩個一個並保存在數組中,之后我只想在屏幕上顯示兩個單獨的字符串。 那是個主意。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package zadania1;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Zadania1
{
public static void main(String[] args)
{
String TextFromFile = "";
Zadania1 zad = new Zadania1();
TextFromFile = zad.NacitajObsahZoSubora("C:\\Users\\Ivan\\Desktop\\test.txt");
String[] pole = TextFromFile.split("[ \\ ]");
System.out.println("Frist matrica " + pole[0] +" Second matrica: " + pole[1] +"");
}
public String NacitajObsahZoSubora(String fileName)
{
String text = "", tmp;
try
{
FileInputStream file = new FileInputStream(fileName);
InputStreamReader input = new InputStreamReader(file);
try (BufferedReader fromFile = new BufferedReader(input))
{
while((tmp = fromFile.readLine()) != null)
{
text = text + "\n" + tmp;
}
System.out.println("Obsah suboru:\n" + text);
}
}
catch(IOException e)
{
}
return text;
}
public void ZapisObsahDoSubora(String fileName, String writeText)
{
try
{
FileOutputStream file = new FileOutputStream(fileName);
OutputStreamWriter output = new OutputStreamWriter(file);
try (PrintWriter toFile = new PrintWriter(output))
{
toFile.println("" + writeText);
}
}
catch (IOException e)
{
}
}
}
只有這一部分向我展示數組超出了反彈范圍:
String[] pole = TextFromFile.split("[ \\ ]");
System.out.println("Frist matrica " + pole[0] +" Second matrica: " + pole[1] +"");
錯誤:
線程“主”中的異常java.lang.ArrayIndexOutOfBoundsException:zadania1.Zadania1.main(Zadania1.java:24)為1
根據我從評論中了解的內容,假設您的輸入形式為:
[1,2,3;4,5,6;][9,8;7,-6;50,61;]
您需要在拆分中使用另一個正則表達式,這涉及到一個回顧:
String input = "[1,2,3;4,5,6;][9,8;7,-6;50,61;]";
String[] pole = input.split("(?<=\\])");
System.out.println("Frist matrica " + pole[0] +" Second matrica: " + pole[1] +"");
// Output:
// Frist matrica [1,2,3;4,5,6;] Second matrica: [9,8;7,-6;50,61;]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.