java 字符串轉化為字符數組的3種實現案例
你可以選擇最簡單的方法解題,但是你需要掌握所有的方法當做知識儲備第一種最簡單,但是其適用前提是輸入: 4(個數) 然后是 1 2 3 4 (也就是輸入數字),放入kk數組之中,輸出1 2 3 4
import java.util.*;public class Main{ public static void main(String args[]) { Scanner cn=new Scanner(System.in); int count=cn.nextInt(); int []kk=new int[count]; for(int i=0;i<count;i++) { int p=cn.nextInt(); kk[i]=p; } for(int i=0;i<kk.length;i++) System.out.println(kk[i]); } }
第二種:
前提是輸入: 4(個數 ) 然后是 1 2 3 4 (也就是輸入數字),放入kk數組之中,輸出1 2 3 4 ,這是另一種思路,作為學習,建議也掌握一下
import java.util.*;public class Main{ public static void main(String args[]) { Scanner cn=new Scanner(System.in); int count=cn.nextInt(); //輸入個數 String str=''; //我們是將第二行輸入的當做字符串來處理的 方法如下: str=cn.nextLine(); //這個的作用就是吃掉輸完數字之后 再輸入字符的回車,這個很重要 str=cn.nextLine(); //這個才是用來讀入 1 2 3 4 這一行,不是一個一個讀入的,是一行 String []k=str.split(' '); //這是用來分割str字符串的 互相分割的條件是 空格 int []kk=new int[k.length]; //這是創建放1 2 3 4的數組 for(int i=0;i<k.length;i++) kk[i]=Integer.parseInt(k[i]); //這是強制轉換成int類型的 for(int i=0;i<kk.length;i++) System.out.println(kk[i]); } }
第三種:
前提是輸入: 4(個數 ) 然后是 1 2 3 4 (也就是輸入數字),放入kk數組之中,輸出1 2 3 4 這次換一個思路,
import java.util.*;public class Main{ public static void main(String args[]) { Scanner cn=new Scanner(System.in); int count=cn.nextInt();//輸入個數 String str=''; //我們是將第二行輸入的當做字符串來處理的 方法如下: str=cn.nextLine(); //這個的作用就是吃掉輸完數字之后 再輸入字符的回車,這個很重要 str=cn.nextLine(); //這個才是用來讀入 1 2 3 4 這一行,不是一個一個讀入的,是一行 int []kk=new int[count]; int r=0; Scanner s=new Scanner(str); for(int i=0;i<str.length();i++) //遍歷字符串 { while(s.hasNextInt()) //判斷字符串挨個是不是數字的 { int t=s.nextInt(); //放入kk數組之中 kk[r]=t; r++; } } for(int j=0;j<kk.length;j++) System.out.println(kk[j]); } }
補充知識:java.將一個字符數組拷貝至另一個字符數組的三種方法
我就廢話不多說了,大家還是直接看代碼吧~
package normalTest;import java.util.Arrays;public class normalTest { public static void main(String[] args) { int[] arr = {1, 2, 3, 4}; int[] arr2 = new int[arr.length]; // 第一種方法:循環添加至新數組中 for (int i = 0; i < arr.length; i++) { arr2[i] = arr[i]; } System.out.println(Arrays.toString(arr2)); // 第二種方法:使用 System.arraycopy // System.arraycopy(數據源, 從上面位置開始復制, 目標數組, 從什么位置開始粘貼, 共復制多少個元素) System.arraycopy(arr, 0, arr2, 0, arr.length); System.out.println(Arrays.toString(arr2)); // 第三種方法:使用 Arrays.copyOf // Arrays.copyOf(原始數組, 新數組長度) arr2 = Arrays.copyOf(arr, arr.length); System.out.println(Arrays.toString(arr2)); }}
以上這篇java 字符串轉化為字符數組的3種實現案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章: