How do you convert from string to char if, for example, the string is entered as an argument in command line (not using scanner). E.g. how would you convert "abcd" to char?
String input = args[0]
String [] part = input.split("");
//splits string into 2 parts (action and characters to encode)
String action = part[0];
// action is what is done to letter i.e. decrypt or encrypt
String plainText = part[1];
char [] letters = plainText.toCharArray();
If you want to convert a String with more than 2 characters to a char array:
String hello = "Hello";
char[] char_array = hello.toCharArray();
Otherwise if you only need one specific char, use hello.charAt(0).
Please notice that you only can store one single 16bit Unicode character inside a char datatype. That's the reason why you need an array for more than 2 characters.
Related
How to convert ASCII values that are substring inside a string to its character? For example:
If I give input as
H105 68u100e33 65r101 89o117?
I need output as
Hi Dude! How Are You?
In the above input after every alphabet or spaces there is an ASCII value.
char[] a = new char[2];
char t;
String temp,output="";
for(int i=0;i<str.length()-1;i++){
a[0]=str.charAt(i);
a[1]=str.charAt(i+1);
if(Character.isDigit(a[0])){
if(Character.isDigit(a[1])){
String con=String.valueOf(a[0])+String.valueOf(a[1]);
int n=Integer.parseInt(con);
output=output+(char)n;
}else{
//nothing
}
}else{
output=output+a[0];
}
}
System.out.println("output : "+output);
I have tried something like this, and it fails at 3 digit ASCII values and also sometimes I face array index outofbound error due to charAt(i+1) statements.
How to change that ASCII values to its char and form a sentence?
You have to create your algorithm based on the phrase "Get all the digits first, and then for each one, replace it with its ASCII value"
So,
public static void main(String[] args)
{
String input = "H105 68u100e33 65r101 89o117?";
// Get all the digits by replacing the non-digits with space
// And then split the string with space char to get them as array
final String[] digits = input.replaceAll("\\D+"," ").trim().split(" ");
// For each one, replace the main input with the ascii value
for (final String digit : digits)
input = input.replaceAll(digit, Character.toString(Integer.parseInt(digit)));
System.out.println(input);
}
Try this.
static final Pattern NUM = Pattern.compile("\\d+");
public static void main(String[] args) {
String input = "H105 68u100e33 65r101 89o117?";
String output = NUM.matcher(input)
.replaceAll(m -> Character.toString(Integer.parseInt(m.group())));
System.out.println(output);
}
output:
Hi Dude! Are You?
NUM is a pattern that matches one or more digits.
NUM.matcher(input).replaceAll() replaces all characters that match this pattern in input. m-> Character.toString(Integer.parseInt(m.group())) converts the matched numeric string to an integer and then converts to the string corresponding to that character code.
I need a java regex to answer my question.
this is my code:
char[] array = s.split("regex");
First replace non-letter characters with blank space, then convert String to char array:
char[] onlyLetters = "regex".replaceAll("[^A-Za-z]+", "").toCharArray();
As you said in your comment below your question, what you really want, is to get the individual characters of that given string, which can be achieved by the toCharArray() method in the String class.
String s = "ABCDEfghi1234";
char[] chars = s.toCharArray();
If you also need to limit the resulting chars to a defined set of characters, you have to remove all others from the string first, which can be done with a simple regex-replace.
String s = "ABCDEfghi1234_.,-DSsf";
s = s.replaceAll("[^A-Za-z]", "");
char[] chars = s.toCharArray();
The split method you used is normally used to split strings at defined positions, e.g. if you want to split a sentence, separated by spaces.
String sentence = "The quick brown fox jumps over the lazy dog";
String[] words = sentence.split("\\s");
// words now contains the extracted words of the sentence
// words[0] == "The"
// words[1] == "quick"
// ...
I have a String containing ASCII representation of a character i.e.
String test = "0x07";
Is there a way I can somehow parse it to its character value.
I want something like
char c = 0x07;
But what the character exactly is, will be known only by reading the value in the string.
You have to add one step:
String test = "0x07";
int decimal = Integer.decode(test);
char c = (char) decimal;
For example:
String word = "schnucks";
word[1] = 'x'; // would this access the C and turn it to an x?
If the above code is not correct, is there a way, besides converting it from a string to a char array to access the individual indices?
Strings in Java are immutable. You can read a char from a specific index with charAt(int index) but you can not modify it. For that you would need to convert to a char array as you suggested and then build a new string from the array.
You can try replace():
String word = "schnucks";
word = word.replace("c", "x");//<-- "sxhnucks", only first occurrence
Also there is replaceAll():
String word = "schnucks";
word = word.replaceAll("c", "x");//<-- "sxhnuxks", all occurrences
To access the elements of a String by index, first convert to an array of chars.
String word = "schnucks";
char[] array = word.toCharArray();
Then you are free to change any letter as you wish. e.g.
array[4] = 'a';
To retrieve the modified String, simply use
word = new String(array);
which returns a String containing the word schnacks.
well you can use charAt(int index) method to access character at your specified index.
But for changing characters of the string you can use StringBuilder class and use .setCharAt(int index, char character) method.
You can't change characters in a String because Strings are immutable in Java.
As mentioned in the Documentation:
Strings are constant; their values cannot be changed after they are created.
To read a character from a String, use charAt
Returns the char value at the specified index. An index ranges from 0 to length() - 1.
To get a String with only a certain character changed, you can do as follows:
String word = "geography";
int indexToChange = 3;
char newCharacter = 'x';
String newword = word.substring(0, indexToChange - 1) + newCharacter + word.substring(indexToChange, word.length());
System.out.println(newword);
In Java, is there a simple method to convert the format of a given string? For example, I have the string "test22". I'd like the binary value and hex value. As well as possibly the ascii values of each character?
My solution would be to take the String, convert it to a char array, and then convert the integer values of the char array into binary or hex through the Integer.toBinaryString() or Integer.toHexString() or Integer.toOctalString() if you would like.
just replace binary string with hex and the function will do the same thing
public String convertToBinary(String str){
char [] array = str.toCharArray();
String binaryToBeReturned = "";
for(int i=0;i<str.length();i++){
binaryToBeReturned += Integer.toBinaryString((int)array[i]) + " ";
}
return binaryToBeReturned;
}
Also to get the ASCII values of the String int value = (int)string.charAt(i); will get the ASCII value.
I added a space just for formatting, not sure how you needed it formatted, and this is just a simple implementation.