Java string to character conversion

How to convert/parse from String to char in java?

In Java, you can convert a string to a character using the charAt() method of the String class. This method takes an index as an argument and returns the character at that index.

String str = "hello"; char ch = str.charAt(0); // ch will be 'h'

You can also use the toCharArray() method to convert a string to an array of characters:

String str = "hello"; char[] chars = str.toCharArray(); // chars will be ['h', 'e', 'l', 'l', 'o']

Note that if you want to convert a single-character string to a character, you can simply use the char type’s parse method, like this:

String str = "h"; char ch = str.charAt(0); // ch will be 'h'

You can also use the char type’s parse method to convert a string to a character:

String str = "h"; char ch = Character.parseChar(str); // ch will be 'h'

Finally, you can use the Character.toString() method to convert a character to a string:

char ch = 'h'; String str = Character.toString(ch); // str will be "h"

BookDuck

Источник

Java string to character conversion

Let’s see another example to convert all characters of a string into character.

char at 0 index is: h char at 1 index is: e char at 2 index is: l char at 3 index is: l char at 4 index is: o

Java String to char Example: toCharArray() method

Let’s see the simple code to convert String to char in java using toCharArray() method. The toCharArray() method of String class converts this string into character array.

char at 0 index is: h char at 1 index is: e char at 2 index is: l char at 3 index is: l char at 4 index is: o

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry
Читайте также:  Https statais mkrf ru index html

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

1. Various ways to convert String to Character:

1.1 Iterate through String using regular for-loop and get character at each position/index using charAt(index) method

  • This method can be used to convert String into primitive char data-type
  • In this approach, for each iteration we will get single character with index-position

Method signature:

public char charAt(int index);

ConvertStringIntoCharacterUsingForLoop.java

package in.bench.resources.string.to.character.conversion; public class ConvertStringIntoCharacterUsingForLoop < public static void main(String[] args) < // String String str1 = "Bench"; System.out.println("Ex 1. Sample string 'Bench'\n"); // 1. converting String to char for(int index = 0; index < str1.length(); index ++) < // retrieving each char using charAt(index) System.out.println("char value at " + index + " index-position is : " + str1.charAt(index)); >// UPPER-CASE - String with all upper-case String str2 = "GOOGLE"; System.out.println("\nEx 2. " + "All upper-case string 'GOOGLE'\n"); // 2. converting String to char for(int index = 0; index < str2.length(); index ++) < // retrieving each char using charAt(index) System.out.println("char value at " + index + " index-position is : " + str2.charAt(index)); >// LOWER-CASE - String with all lower-case String str3 = "oracle"; System.out.println("\nEx 3. " + "All lower-case string 'oracle'\n"); // 3. converting String to char for(int index = 0; index < str3.length(); index ++) < // retrieving each char using charAt(index) System.out.println("char value at " + index + " index-position is : " + str3.charAt(index)); >> >
Ex 1. Sample string 'Bench' char value at 0 index-position is : B char value at 1 index-position is : e char value at 2 index-position is : n char value at 3 index-position is : c char value at 4 index-position is : h Ex 2. All upper-case string 'GOOGLE' char value at 0 index-position is : G char value at 1 index-position is : O char value at 2 index-position is : O char value at 3 index-position is : G char value at 4 index-position is : L char value at 5 index-position is : E Ex 3. All lower-case string 'oracle' char value at 0 index-position is : o char value at 1 index-position is : r char value at 2 index-position is : a char value at 3 index-position is : c char value at 4 index-position is : l char value at 5 index-position is : e

1.2 Assign single character of String to char value directly using charAt(0) method

  • This method converts String consisting of single character into primitive char data-type
  • Here, directly accessing index 0 using charAt() method because we are sure that there is only one character present in the string (unlike previous way-1)
Читайте также:  Php using functions with variables

Method signature:

public char charAt(int index);

ConvertStringIntoCharacterUsingCharAtMethod.java

package in.bench.resources.string.to.character.conversion; public class ConvertStringIntoCharacterUsingCharAtMethod < public static void main(String[] args) < // String with single character in upper-case String str1 = "A"; // 1. converting String to char char chValue1 = str1.charAt(0); System.out.println("1. Converted upper-case" + " char-value is : " + chValue1); // String with single character in upper-case String str2 = "x"; // 2. converting String to char char chValue2 = str2.charAt(0); System.out.println("\n2. Converted lower-case" + " char-value is : " + chValue2); >>
1. Converted upper-case char value is : A 2. Converted lower-case char value is : x

Q) What if we want to convert primitive char data-type to Character wrapper-type or vice-versa ?

  • Auto-boxing feature available from Java 1.5 version
  • So, converting primitive data-type to wrapper-type can easily be done, by directly assigning
  • Let’s see one example based on this auto-boxing feature

2. Auto-boxing and un-boxing feature from Java 1.5 version:

  • charAt() method returns primitive char data-type, but it can be easily used as Character wrapper-type
  • as auto-boxing feature helps to convert primitive data-type to respective wrapper-types
  • Newly created Character wrapper-type object can be easily converted to primitive char data-type
  • let’s see one example on this auto-boxing feature, at the very end

AutoBoxingFeatureForCharConversion.java

package in.bench.resources.string.to.character.conversion; public class AutoBoxingFeatureForCharConversion < public static void main(String[] args) < // String with upper-case String str1 = "C"; // converting String to char char chValue1 = str1.charAt(0); // 1. Auto-Boxing - converting char to Character Character chAutoBoxing = chValue1; System.out.println("1. Auto-Boxing : " + chAutoBoxing); // String with lower-case String str2 = "z"; // converting String to Character Character chValue2 = new Character(str2.charAt(0)); // 2. Un-Boxing - converting Character to char char chUnBoxing = chValue2; System.out.println("\n2. Un-Boxing : " + chUnBoxing); >>
1. Auto-Boxing : C 2. Un-Boxing : z

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

  • Java – String to int conversion – 3 ways
  • Java – Integer to String conversion – 6 ways
  • Java – String to float conversion – 3 ways
  • Java – Float to String conversion – 6 ways
  • Java – String to double conversion – 3 ways
  • Java – Double to String conversion – 6 ways
  • Java – String to long conversion – 3 ways
  • Java – Long to String conversion – 6 ways
  • Java – String to boolean conversion – 3 ways
  • Java – Boolean to String conversion – 6 ways
  • Java – String to char conversion
  • Java – Character to String conversion – 6 ways
  • Java – String to char[] array conversion – 4 ways
  • Java – Character[] array to String conversion – 5 ways
  • Java – String to byte conversion – 3 ways
  • Java – Byte to String conversion – 5 ways
  • Java – String to byte[] array conversion
  • Java – Byte[] array to String conversion
  • Java – String to short conversion – 3 ways
  • Java – Short to String conversion – 5 ways
  • Java – StringBuffer to String conversion and vice-versa
  • Java – StringBuilder to String conversion and vice-versa
  • Java – String to Date conversion
  • Java – Date to String conversion
Читайте также:  Python сделать exe pyinstaller

References:

  • https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
  • https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html
  • https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
  • https://docs.oracle.com/javase/tutorial/java/data/converting.html
  • https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
  • https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html
  • https://docs.oracle.com/javase/tutorial/java/data/strings.html
  • https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
  • https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
  • https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
  • https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html

Happy Coding !!
Happy Learning !!

Источник

String to char array java — convert string to char

String to char array java - convert string to char

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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

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.

  1. char[] toCharArray() : This method converts string to character array. The char array size is same as the length of the string.
  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.
  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.

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

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. In getChars example, first 7 characters of str will be copied to chars1 starting from its index 0. That’s all for converting string to char array and string to char java program. Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью