convert string to character array in Java.

How to convert string to character in Java, In certain occasions, it is necessary to convert a to a character array in Java programs or convert a to a specific character starting from a certain index.

Convert a Java into a character.

Let’s explore the three methods in the class before we examine a Java program for converting a to a char array.
toCharArray() is a method that converts a into a character array, where the size of the array is equal to the length of the.
charAt(int index) retrieves the character at a specified
index in the.
If the index value is negative or exceeds the length of the, will throw aIndexOutOfBoundsException
getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) is a useful method for converting a portion of the into a character array.
The first two parameters determine the starting and ending index of the, with the last character to be copied being at index srcEnd-1.The characters are then copied into the char array, starting at index dstBegin and ending at dstBegin + (srcEnd-srcBegin) – 1.

Let’s examine a basic example of a Java program that converts a into a character array.

package com.scdev.string;

public classToCharJava {

	public static void main(String[] args) {
		String str = "scdev";
		
		//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 characters to char array
		char[] chars1 = new char[7];
		str.getChars(0, 7, chars1, 0);
		System.out.println(chars1);
		
	}

}

The program above demonstrates the straightforward and explicit use of the toCharArray and charAt methods. That concludes the process of converting a to a char array in Java. For more information, refer to the API documentation.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds