Java Converting binary sequence to char - java

I looked for this about an hour now, but couldn't get any advise specific to my problem. What I'd like to do is take a string of 0's and 1's and manipulate a char that it fits the given String pattern. For example:
char c = 'b'
String s = "00000000 01100001";
Now I'd like to manipulate the bits in c, so that they match the bit pattern specified in s. As result c would be printed as 'a' (if I'm not completely wrong about it). Any help appreciated!

You can do
char a = (char) Integer.parseInt("0000000001100001", 2);

To do the conversion from binary string to Integer, use parseInt with the 2nd argument as 2.
int temp = Integer.parseInt("01100001", 2);
You can modify with binary operators (&,|,^), but if what you really want is to just assign a variable, you can do it with casts.
char c = 'c';
System.out.println((char)(c&temp));
System.out.println((char)temp);

How about:
String s = "00000000 01100001";
String[] w = s.split(" ");
char c = (char)(Integer.parseInt(w[0], 2) * 256 + Integer.parseInt(w[1], 2));
This allows for the leading zeroes of each byte to be omitted. If you know they're there, you can just replace the space out of the string and use a single parseInt() call:
char c = (char)Integer.parseInt(s.replace(" ", ""), 2);

Related

String with one character can be casted to char?

String message = "a";
char message1 = (char) message;
System.out.println(message1);
Gives me an output error,
This should be converted with ease because the string is one character "a"
I know I can do it explicitly sorry, why the two are incompatible to cast if they are storing the same (only one character)?
As you've seen, no, you cannot cast a single character String to a char. But you could extract it explicitly:
String message = "a";
char message1 = message.charAt(0);
No you cannot do that. You can cast a char to Character because the Character object type is the "boxed" version of the char base type.
Character charObject = (Character) 'c';
char charBase = (char) charObject;
actually, because of auto-boxing and auto-unboxing, you don't need the explicit cast:
Character charObject = 'c';
char charBase = charObject;
However, a String is an object type much like any other object type. That means you cannot cast it to char, you need to use the charAt(int index) method to retrieve characters from it.
Beware though that you may want to use codePointAt(int index) instead, since Unicode code points may well extend out of the 65536 code points that can be stored in the 16 bits that a char represents. So please make sure that no characters defined in the "supplementary planes" are present in your string when using charAt(int index).
As in Java any type can be converted to String, it is possibly to directly append characters to a string though, so "strin" + 'g' works fine. This is also because the + operator for String is syntactic sugar in Java (i.e. other objects cannot use + as operator, you would have to use a method such as append()). Do remember that it returns a new string rather than expanding the original "strin" string. Java strings are immutable after all.
You cannot cast a String to a char. Below is a snippet to always pick the first character from the String,
char c = message.charAt(0);
In case you want to convert the String to a character array, then it can be done as,
String g = "test";
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['t','e','s','t']
A String with one char is more akin to a char[1]. Regardless, retrieve the character directly:
String ex = /* your string */;
if (!ex.isEmpty()) {
char first = ex.charAt(0);
}

How to replace first and middle char in string

I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.

How do I add int. to char and string to get "abc" in the output? (For Java)

So I was given this formatted problem and told to fix the format in order to get the output.
int x = 0;
int y = 1;
char p = 'a';
String s = "c"
The format is
(p + x + p + y + s)
And I'm supposed to change this (as long as I use x,y,p,s) to make the output be "abc."
How do I do this? The farthest I've gotten is that
System.out.println(p=(char)((int)p+x));
And that makes the output "a".
What do I do? Help please! I'm a very new programmer.
Thanks in advance.
I have tried the following which works:
int x = 0;
int y = 1;
char p = 'a';
String s = "c";
StringBuilder builder = new StringBuilder();
builder.append((char)((int)p+x)).append((char)((int)p+y)).append(s);
System.out.println(builder.toString());
It prints: abc
System.out.println(p + String.valueOf((char)(p+y)) + s);
Thanks for asking this question, I probably would have never known that String constructor doesn't take only a single character as a parameter.
For clarity:
String.valueOf() returns the character p+y as a String.
When you use + between all the three, they get concatenated.
Edit- A note on what you were doing with your code is that in the line:
System.out.println(p=(char)((int)p+x));
You here are overwriting the value of character variable p which already stores the value of character 'a' with the value of p+x. Here, x is 0 so it will be added to the ASCII value of character stored in p, i.e 'a' and results in the same.
Another note is that even if x was something else other than 0, you didn't have to first type cast into (int), you could have directly type casted it into (char). And since the variable where you are storing that operation is a character itself, you don't need any type casting at all!

How to replace some character in a string with a single character of type char?

As an example I have abcdbab and I want to replace all ab with A.
The output is AcdbA.
I try this one but it gives an error.
char N = 65;
String S = "abcdbab";
S = S.replaceAll("ab", N);
System.out.print(S);
Is there any method to do this?
Use String.replace(CharSequence,CharSequence) (remember String is immutable, so either use the result or assign it back) like
String str = "abcdbab";
System.out.println(str);
str = str.replace("ab", "A");
System.out.println(str);
Output is
abcdbab
AcdbA
Just change the following line:
char N = 65;
to
String N = "A";
and it'll work fine.
There is no such method String#replace(CharSequence, char), you will need to find the one that is closes to your needs and adjust to it, for example, there is a String#replaceAll(CharSequence, CharSequence) method and char can be represented as a CharSequence (or a String), for example...
S = S.replaceAll("ab", Character.toString(N));
You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others
You can also change
S = S.replaceAll("ab", N);
to
S = S.replaceAll("ab", "" + N);
referencing here, http://www.tutorialspoint.com/java/java_string_replaceall.htm replaceAll takes a String, String not String, Char

Concat the two first characters of string

I have a String s = "abcd" and I want to make a separate String c that is let's say the two first characters of String s. I use:
String s = "abcd";
int i = 0;
String c = s.charAt(i) + s.charAt(i+1);
System.out.println("New string is: " + c);
But that gives error: incompatible types. What should I do?
You should concatenate two Strings and not chars. See String#charAt, it returns a char. So your code is equivalent to:
String c = 97 + 98; //ASCII values for 'a' and 'b'
Why? See the JLS - 5.6.2. Binary Numeric Promotion.
You should do:
String c = String.valueOf(s.charAt(i)) + String.valueOf(s.charAt(i+1));
After you've understood your problem, a better solution would be:
String c = s.substring(0,2)
More reading:
ASCII table
Worth knowing - StringBuilder
String#substring
What you should do is
String c = s.substring(0, 2);
Now why doesn't your code work? Because you're adding two char values, and integer addition is used to do that. The result is thus an integer, which can't be assigned to a String variable.
String s = "abcd";
First two characters of the String s
String firstTwoCharacter = s.substring(0, 2);
or
char c[] = s.toCharArray();
//Note that this method simply returns a call to String.valueOf(char)
String firstTwoCharacter = Character.toString(c[0])+Character.toString(c[1]);
or
String firstTwoCharacter = String.valueOf(c[0])+ String.valueOf(c[1]);

Categories

Resources