字符串到字符数组 Java - 将字符串转换为字符

有时我们必须将 String 转换为 java 程序中的字符数组,或者从特定索引转换一个字符串为 char。

关键字: char java

string to char java, string to char array String class has three methods related to char. Let's look at them before we look at a java program to convert string to char array.

此方法将字符串转换为字符串。字符串大小与字符串的长度相同 2. charAt(int index):此方法将字符返回特定字符串的索引。此方法将字符串转换为StringIndexOutOfBoundsException,如果字符串的索引值是负的或大于字符串的长度 3.getChars(int srcBegin,int srcEnd, char dst[], int dstBegin):这是当你想要将字符串的一部分转换为字符串时非常有用的方法。 第一两个参数定义字符串的开始和结束;最后一个字符被复制在 index srcEnd-1. 字符被复制到字

让我们来看看一个简单的 string to char array java 程序的例子。

 1package com.journaldev.string;
 2
 3public class StringToCharJava {
 4
 5    public static void main(String[] args) {
 6    	String str = "journaldev";
 7    	
 8    	//string to char array
 9    	char[] chars = str.toCharArray();
10    	System.out.println(chars.length);
11    	
12    	//char at specific index
13    	char c = str.charAt(2);
14    	System.out.println(c);
15    	
16    	//Copy string characters to char array
17    	char[] chars1 = new char[7];
18    	str.getChars(0, 7, chars1, 0);
19    	System.out.println(chars1);
20    	
21    }
22
23}

在上面的程序中,toCharArraycharAt的使用非常简单和清晰。在getChars的例子中,第7个字符将被复制到chars1,从其索引开始。

Published At
Categories with 技术
Tagged with
comments powered by Disqus