首页 > 编程知识 正文

将字符串存入数组java(如何将字符串存入字符数组)

时间:2023-12-11 12:54:43 阅读:314459 作者:TBWV

本文目录一览:

请问,JAVA中如何实现将一字符串一一导入数组

用方法toCharArray

public char[] toCharArray()

该方法把该字符串转换成一个新的字符数组。

String str="abcdefg";

char a[];

a=str.toCharArray();

也可以用方法:

getChars

public void getChars(int srcBegin,

int srcEnd,

char dst[],

int dstBegin)

从该字符串中拷贝字符到目的字符数组中。

第一个要复制的字符在索引 srcBegin 处; 最后一个要复制的字符在索引 srcEnd-1 处(因此要复制的字符总数就是 srcEnd-srcBegin) 。要复制到 dst 子数组的字符开始于索引 dstBegin ,结束于索引:

dstbegin + (srcEnd-srcBegin) - 1

参数:

srcBegin - 要复制的字符串中第一个字符的索引。

srcEnd - 要复制的字符串中最后一个字符的索引。

dst - 目标数组。

dstBegin - 目标数组中的开始偏移量。

String str="abcdefg";

char a[];

str.getChars(0,str.length(),a,0);

java中如何将一个字符串赋给一个数组

赋给字符数组:char[] chars = s.toCharArray();

赋给字节数组:byte[] bytes = s.getBytes()

因为这里是字节,所以直接打印出来显示不是abcd,先要转换为char类型的再打印

JAVA中怎样把用户输入的字符串存入数组中?

import java.util.Scanner;

import java.util.InputMismatchException;

public class saveInputToArr {

public static void main(String[] args) {

Scanner scan = null;

try {

scan = new Scanner(System.in);

System.out.print( "请输入个数: " );

int inputNum = scan.nextInt();

if( inputNum = 0 ) {

throw new Exception( "输入有误" );

}

System.out.println( "请输入数字: " );

int arr[] = new int[inputNum];

int num = 0;

int count = 0;

while( count inputNum ) {

num = scan.nextInt();

arr[count] = num;

count++;

}

for( int i = 0; i arr.length; i++ ) {

System.out.print( arr[i] + "  " );

}

} catch ( Exception e ) {

throw new InputMismatchException( "u8f93u5165u6709u8befu002cu0020u8bf7u91cdu65b0u8f93u5165" );

} finally {

try {

if ( scan != null ) {

scan.close();

}

} catch ( Exception e2 ) {

e2.printStackTrace();

}

}

}

}

运行结果为:

请输入个数: 2

请输入数字:99

123

99 123

扩展资料

Java从输入中读取一个数组

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);

String str = sc.nextLine().toString();//用nextLine()可以读取一整行,包括了空格,next()却不能读取空格

String arr[] = str.split(" ");//拆分字符串成字符串数组

int a[] = new int[arr.length];

for(int j = 0; j a.length; j++)

{

a[j] = Integer.parseInt(arr[j]);

System.out.print(a[j] + " ");

}

}

}

Java 我需要把一个字符串专为数组怎么办?

java 中要将一个字符串转换成一个字符数组需要使用 String 类中提供的 toCharArray() 方法进行操作.实例如下:

String str = "abcde";//这是一个string类型的字符串

char[] ch = str.toCharArray();//使用string类型的tocharArray()方法进行转换。

用java将字符串存入数组

一行存入一个数组吗?

String[] array;

string str;

int i;

FileReader word = new FileReader("word.txt");

BufferedReader br = new BufferedReader(word);

while((str = br.readLine()) != null){

    array[i] = str;

    i++;

}

java 如何把string 加入数组中

可以使用split函数将String 字符串转化为数组

split 方法 

将一个字符串分割为子字符串,然后将结果作为字符串数组返回。

例子:

String []arr1 = "String".split("");

for(int i = 0;iarr1.length;i++){

System.out.println(arr1[i]);

}

结果:

S

t

r

i

n

g

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。