簡體   English   中英

將空格分隔的字符串值(由整數組成)存儲到java中的字節數組中

[英]Storing string value (consisting of integers) seperatated by space into byte array in java

我正在編寫一個Java程序,該程序需要將字符串的值存儲到字節數組中(整數值在字符串中用空格分隔)。 誰能幫我解決這個問題。

例如:

輸入:String str =“ 71 17 -93 -104”;

要求的輸出:

// Byte array variable, byte[] myByte

myByte[0] = 71,

myByte[1] = 17,

myByte[2] = -93,

myByte[3] = -104

但是,我已經將字符串值存儲在整數數組中,但是我感到很難將其存儲在字節數組中。 我曾用於在整數數組中存儲字符串值的代碼:

       `String numbers = "71 17 -93 -104";
        String[] nums = numbers.split(" ");
        for(int i=0; i< nums.length; i++)
        {
            System.out.println(nums[i]); 
        }
        int StrArrLen = nums.length;
        int[] myArray = new int[StrArrLen];
        for(int i=0; i< StrArrLen; i++)
        {
            myArray[i] = Integer.parseInt(nums[i]); 
        }
        System.out.println("\nResult:");
        for(int i=0; i< StrArrLen; i++)
        {
            System.out.println(myArray[i]); 
        }`

問候

像這樣將整數類型轉換為字節。 您必須確保整數在-128到127之間。

String numbers = "71 17 -93 -104";
    String[] nums = numbers.split(" ");
    for(int i=0; i< nums.length; i++)
    {
        System.out.println(nums[i]); 
    }
    int StrArrLen = nums.length;
    byte[] myArray = new byte[StrArrLen];
    for(int i=0; i< StrArrLen; i++)
    {
        myArray[i] = (byte)Integer.parseInt(nums[i]);

    }
    System.out.println("\nResult:");
    for(int i=0; i< StrArrLen; i++)
    {
        System.out.println(myArray[i]); 
    }

暫無
暫無

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

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