我有一個字符串,如下所示2 4 12 12 yellow Hi how are you我想像這樣拆分字符串{2,2,12,12,yellow, Hi how are you},以便將列表中的項目作為構造函數中的參數傳遞。有什么幫助嗎?
1 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
簡單的答案是拆分字符串:
String[] fragments = theString.split(" ", 6);
鑒于片段具有特定含義(并且可能您希望其中一些作為非字符串類型),使用 a 可能更具可讀性Scanner:
Scanner sc = new Scanner(theString);
int x = sc.nextInt();
int y = sc.nextInt();
int width = sc.nextInt();
int height = sc.nextInt();
String color = sc.next();
String message = sc.nextLine();
如果您從文件或標準輸入中讀取這些字符串,這種方法也更容易:只需Scanner在 FileReader/InputStream 上創建。
添加回答
舉報
0/150
提交
取消