簡體   English   中英

如何拆分一串 8 個數字並分別訪問它們?

[英]How do I split a string of 8 numbers and access each of them individually?

我編寫了我的程序,以由 8 個數字組成的字符串的形式從用戶那里獲取輸入。 我想拆分這 8 個數字,以便我可以單獨訪問它們中的每一個。 它是否與 Python 一樣,我會使用 input[1] 左右來訪問它們,我該如何拆分它們?

我不確定 go 有什么辦法。

Scanner sc = new Scanner(System.in);
String input;
System.out.println("Please type your number in 8 bit binary form: ");
input = sc.nextLine();

到目前為止代碼運行良好,只是不知道如何將輸入拆分為 8 個不同數字的數組。

你可以試試這么簡單的東西!

for (char vl:input.toCharArray()){
  System.out.println(vl);
}

問題是您的拆分限制是什么。

您可以使用charAt() function依次獲取字符串中所有字符的值。

或者,您可以執行以下操作:

String[] array = input.split(""); //split your string into string array using regex to define delimiter
    ArrayList<Integer> numbers = new ArrayList<>(); //initialize array of numbers
    for (String s: array) {
        numbers.add(Integer.parseInt(s)); // parse each string as Integer value
    }

所以你會有數字數組,然后你可以通過它的索引訪問每個數字。

為什么不這樣做

String[] binaryArray = input.split("");

暫無
暫無

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

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