欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java 字符串轉(zhuǎn)化為字符數(shù)組的3種實現(xiàn)案例

 更新時間:2020年10月20日 09:37:48   作者:蜀人ing  
這篇文章主要介紹了java 字符串轉(zhuǎn)化為字符數(shù)組的3種實現(xiàn)案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

你可以選擇最簡單的方法解題,但是你需要掌握所有的方法當做知識儲備第一種最簡單,但是其適用前提是輸入: 4(個數(shù)) 然后是 1 2 3 4 (也就是輸入數(shù)字),放入kk數(shù)組之中,輸出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(個數(shù) ) 然后是 1 2 3 4 (也就是輸入數(shù)字),放入kk數(shù)組之中,輸出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(); //輸入個數(shù) 
 String str=""; //我們是將第二行輸入的當做字符串來處理的 方法如下:
 str=cn.nextLine();  //這個的作用就是吃掉輸完數(shù)字之后 再輸入字符的回車,這個很重要
 str=cn.nextLine();  //這個才是用來讀入 1 2 3 4 這一行,不是一個一個讀入的,是一行
 
 String []k=str.split(" ");  //這是用來分割str字符串的  互相分割的條件是 空格
 int []kk=new int[k.length]; //這是創(chuàng)建放1 2 3 4的數(shù)組
 for(int i=0;i<k.length;i++)
  kk[i]=Integer.parseInt(k[i]); //這是強制轉(zhuǎn)換成int類型的
 
 for(int i=0;i<kk.length;i++)
  System.out.println(kk[i]);  
 } 
}

第三種:

前提是輸入: 4(個數(shù) ) 然后是 1 2 3 4 (也就是輸入數(shù)字),放入kk數(shù)組之中,輸出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();//輸入個數(shù) 
 String str="";   //我們是將第二行輸入的當做字符串來處理的 方法如下:
 str=cn.nextLine();  //這個的作用就是吃掉輸完數(shù)字之后 再輸入字符的回車,這個很重要
 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())  //判斷字符串挨個是不是數(shù)字的
  {
  int t=s.nextInt();  //放入kk數(shù)組之中
  kk[r]=t;
  r++;
  }
 }
 for(int j=0;j<kk.length;j++)
  System.out.println(kk[j]);   
 } 
}

補充知識:java.將一個字符數(shù)組拷貝至另一個字符數(shù)組的三種方法

我就廢話不多說了,大家還是直接看代碼吧~

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];

    // 第一種方法:循環(huán)添加至新數(shù)組中
    for (int i = 0; i < arr.length; i++) {
      arr2[i] = arr[i];
    }
    System.out.println(Arrays.toString(arr2));

    // 第二種方法:使用 System.arraycopy
    // System.arraycopy(數(shù)據(jù)源, 從上面位置開始復制, 目標數(shù)組, 從什么位置開始粘貼, 共復制多少個元素)
    System.arraycopy(arr, 0, arr2, 0, arr.length);
    System.out.println(Arrays.toString(arr2));

    // 第三種方法:使用 Arrays.copyOf
    // Arrays.copyOf(原始數(shù)組, 新數(shù)組長度)
    arr2 = Arrays.copyOf(arr, arr.length);
    System.out.println(Arrays.toString(arr2));
  }
}

以上這篇java 字符串轉(zhuǎn)化為字符數(shù)組的3種實現(xiàn)案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論