java字符串转字符串数组_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

{

int p=cn.nextInt();

kk[i]=p;

}

for(int i=0;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

kk[i]=Integer.parseInt(k[i]); //这是强制转换成int类型的

for(int i=0;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

{

while(s.hasNextInt()) //判断字符串挨个是不是数字的

{

int t=s.nextInt(); //放入kk数组之中

kk[r]=t;

r++;

}

}

for(int j=0;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种实现案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值