char数组转换成字符串_将字符串转换为char数组java –将字符串转换为char

char数组转换成字符串

Sometimes we have to convert String to the character array in java programs or convert a string to char from specific index.

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

字符串到char Java (String to 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.


字符串类具有与char相关的三种方法。 让我们先看一下它们,然后再看一个将字符串转换为char数组的Java程序。

  1. char[] toCharArray(): This method converts string to character array. The char array size is same as the length of the string.

    char[] toCharArray() :此方法将字符串转换为字符数组。 char数组的大小与字符串的长度相同。
  2. char charAt(int index): This method returns character at specific index of string. This method throws StringIndexOutOfBoundsException if the index argument value is negative or greater than the length of the string.

    char charAt(int index) :此方法在字符串的特定索引处返回字符。 如果索引参数值是负数或大于字符串的长度,则此方法将引发StringIndexOutOfBoundsException
  3. getChars(int srcBegin, int srcEnd, char dst[], int dstBegin): This is a very useful method when you want to convert part of string to character array. First two parameters define the start and end index of the string; the last character to be copied is at index srcEnd-1. The characters are copied into the char array starting at index dstBegin and ending at dstBegin + (srcEnd-srcBegin) – 1.

    getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) :当您要将一部分字符串转换为字符数组时,这是一种非常有用的方法。 前两个参数定义字符串的开始和结束索引; 最后要复制的字符在索引srcEnd-1处。 将字符复制到char数组中,该数组从索引dstBegin开始,以dstBegin +(srcEnd-sr​​cBegin)– 1结尾。

Let’s look at a simple string to char array java program example.

让我们看一个简单的字符串到char数组的Java程序示例。

package com.journaldev.string;

public class StringToCharJava {

	public static void main(String[] args) {
		String str = "journaldev";
		
		//string to char array
		char[] chars = str.toCharArray();
		System.out.println(chars.length);
		
		//char at specific index
		char c = str.charAt(2);
		System.out.println(c);
		
		//Copy string characters to char array
		char[] chars1 = new char[7];
		str.getChars(0, 7, chars1, 0);
		System.out.println(chars1);
		
	}

}

In above program, toCharArray and charAt usage is very simple and clear.

在上面的程序中, toCharArraycharAt用法非常简单明了。

In getChars example, first 7 characters of str will be copied to chars1 starting from its index 0.

getChars示例中,str的前7个字符将从其索引0开始复制到chars1。

That’s all for converting string to char array and string to char java program.

这就是将字符串转换为char数组并将字符串转换为char java程序的全部操作。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/794/string-char-array-java

char数组转换成字符串

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值