Java – How to convert Char to String
A Java example to show you how to convert a Char
into a String
and vise verse.
ConvertCharToString.java
package com.mkyong.utils;
public class ConvertCharToString {
public static void main(String[] args) {
String website = "https://mkyong.com";
//convert a String into char
char charH = website.charAt(0); //h
char charP = website.charAt(3);//p
char charM = website.charAt(11);//m
System.out.println(charH);
System.out.println(charP);
System.out.println(charM);
//convert char back to String
String temp = Character.toString(charM);
if ("m".equals(temp)) {
System.out.println("match");
}
}
}
Output
h p m match
you can find some more details in the below link,”http://javadomain.in/char-to-string-in-java/”
You sir, are God sent. The small amount of code you have shown here has been more enlightening than the majority of forums I have searched.
I am now able to figure out how to get the basic concept for ‘reversing text in a file’.
This is what I have so far, it is definitely not complete and does not reverse all the text in a file. However, with the basic concept you have displayed using the toString() method in the Character class, I have the following code in my test driver:
public class ReverseText
{
public static void main(String[] args) throws FileNotFoundException
{
File inputFile = new File(“Solar_System_Info.txt”);
Scanner in = new Scanner(inputFile);
String info = in.nextLine();
char processInfo = info.charAt(info.length()-1);
String reverse = Character.toString(processInfo);
char processInfo2 = info.charAt(info.length()-2);
reverse = reverse + Character.toString(processInfo2);
System.out.println(reverse);
}
Thanks for this, very nice explanation.
this example seems more to be for converting strings to char and why are throwing in the if statment? just confuses the issue
“website.charAt(11)” will return a char and later use “Character.toString()” to convert char to String.
The if statement is used to show that the char is converted into string and can be used for string compare.