首页 > 编程知识 正文

char数组存的是字节还是字符,java里面char数组和字符串转换

时间:2023-05-04 19:06:53 阅读:272780 作者:3409

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 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程序。

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

char[] toCharArray() :此方法将字符串转换为字符数组。 char数组的大小与字符串的长度相同。 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 。 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 arraychar[] chars = str.toCharArray();System.out.println(chars.length);//char at specific indexchar c = str.charAt(2);System.out.println(c);//Copy string characters to char arraychar[] 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.

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

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数组转换成字符串

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