converting a string variable to a char - java

Is there a way to convert a String variable of the type "X" to a character ?
String state = "X";
char c_state = convertToChar(state);
How do I do this ?

You could do:
char c_state = state.charAt(0);

You could also convert it into a char array as follows, which could be quite useful if the String contained more than 1 character.
char[] charArray = state.toCharArray();

This is another approach
char c_state = state.toCharArray()[0];

Related

How to convert string representation of an ASCII value to character

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;

Replace String with character code in Java

Can't figure out how to replace a string with a character in Java. I wanted a function like this:
replace(string, char)
but there's not a function like this in Java.
String str = str.replace("word", '\u0082');
String str = str.replace("word", (char)130);
How do I go about this?
Use a string as the replacement that happens to be only a single character in length:
String original = "words";
String replaced = original.replace("word", "\u0130");
The replaced instance will be equivalent to "İs".
Note also that, from your question, '\u0130' and (char)130 are not the same characters. The \u syntax uses hexadecimal and your cast is using decimal notation.
Very simply:
String orginal = "asdf";
char replacement = 'z';
orginal = original.replace(original, replacement+"");
You asked for a "function" in Java, you can allways create a method like this
public static String replace (String text, char old, char n){
return text.replace(old, n);
}
Then you can call this method as you want
String a = replace("ae", 'e', '3');
In this case the method will return a String with a3 as value, but you can replace not only a char by another, you can replace a String with multiple characters in the same way
public static String replace (String text, String old, String n){
return text.replace(old, n);
}
Then you call this method like this
String a = replace("aes", "es", "rmy");
The result will be a String with army as value
the simplest way:
"value_".replace("_",String.valueOf((char)58 )); //return "value:"
EDIT:
(char)58 //return: ':'
(int)':' //return: 58
Since we want to work with codes and no character we have to pass code to character
another problem to solve is that method "replace" does not take "(String x,char y)"
So we pass our character to String this way:
String.valueOf((char)58) //this is a String like this ":"
Finally we have String from int code, to be replaced.
"String is a sequence of characters"
String s="hello";
char c='Y';
System.out.println(s.replace(s, Character.toString(c)));
Output:
Y

Can you access strings by indices (indexes) in Java?

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);

Split String With Some Constraints In Java

I have a string like this :
12
I want to get split to [2] ignoring 1. Is it possible to do so in java?
You can use the split() method to split on a regex input or, better yet, if you know the exact position or character you want to split at (as seems to be the case here), just use substring() combined with indexOf(). Something like:
String substring = string.substring(0, indexOf("2"));
where string is your original String variable..
If you know the exact index,
String str = "12"
String s = str.substring(1,2); // output 2
or
String s = str.substring(0, indexOf("2")); //output 2
or
char[] chars = str.toCharArray();
char c = chars[1]; // output

How to represent empty char in Java Character class

I want to represent an empty character in Java as "" in String...
Like that char ch = an empty character;
Actually I want to replace a character without leaving space.
I think it might be sufficient to understand what this means: no character not even space.
You may assign '\u0000' (or 0).
For this purpose, use Character.MIN_VALUE.
Character ch = Character.MIN_VALUE;
char means exactly one character. You can't assign zero characters to this type.
That means that there is no char value for which String.replace(char, char) would return a string with a diffrent length.
As Character is a class deriving from Object, you can assign null as "instance":
Character myChar = null;
Problem solved ;)
An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.
You say you want to "replace a character without leaving a space".
If you are dealing with a char[], then you would create a new char[] with that element removed.
If you are dealing with a String, then you would create a new String (String is immutable) with the character removed.
Here are some samples of how you could remove a char:
public static void main(String[] args) throws Exception {
String s = "abcdefg";
int index = s.indexOf('d');
// delete a char from a char[]
char[] array = s.toCharArray();
char[] tmp = new char[array.length-1];
System.arraycopy(array, 0, tmp, 0, index);
System.arraycopy(array, index+1, tmp, index, tmp.length-index);
System.err.println(new String(tmp));
// delete a char from a String using replace
String s1 = s.replace("d", "");
System.err.println(s1);
// delete a char from a String using StringBuilder
StringBuilder sb = new StringBuilder(s);
sb.deleteCharAt(index);
s1 = sb.toString();
System.err.println(s1);
}
As chars can be represented as Integers (ASCII-Codes), you can simply write:
char c = 0;
The 0 in ASCII-Code is null.
If you want to replace a character in a String without leaving any empty space then you can achieve this by using StringBuilder. String is immutable object in java,you can not modify it.
String str = "Hello";
StringBuilder sb = new StringBuilder(str);
sb.deleteCharAt(1); // to replace e character
I was looking for this. Simply set the char c = 0; and it works perfectly. Try it.
For example, if you are trying to remove duplicate characters from a String , one way would be to convert the string to char array and store in a hashset of characters which would automatically prevent duplicates.
Another way, however, will be to convert the string to a char array, use two for-loops and compare each character with the rest of the string/char array (a Big O on N^2 activity), then for each duplicate found just set that char to 0..
...and use new String(char[]) to convert the resulting char array to string and then sysout to print (this is all java btw). you will observe all chars set to zero are simply not there and all duplicates are gone. long post, but just wanted to give you an example.
so yes set char c = 0; or if for char array, set cArray[i]=0 for that specific duplicate character and you will have removed it.
You can't. "" is the literal for a string, which contains no characters. It does not contain the "empty character" (whatever you mean by that).
In java there is nothing as empty character literal, in other words, '' has no meaning unlike "" which means a empty String literal
The closest you can go about representing empty character literal is through zero length char[], something like:
char[] cArr = {}; // cArr is a zero length array
char[] cArr = new char[0] // this does the same
If you refer to String class its default constructor creates a empty character sequence using new char[0]
Also, using Character.MIN_VALUE is not correct because it is not really empty character rather smallest value of type character.
I also don't like Character c = null; as a solution mainly because jvm will throw NPE if it tries to un-box it. Secondly, null is basically a reference to nothing w.r.t reference type and here we are dealing with primitive type which don't accept null as a possible value.
Assuming that in the string, say str, OP wants to replace all occurrences of a character, say 'x', with empty character '', then try using:
str.replace("x", "");
char ch = Character.MIN_VALUE;
The code above will initialize the variable ch with the minimum value that a char can have (i.e. \u0000).
this is how I do it.
char[] myEmptyCharArray = "".toCharArray();
You can do something like this:
mystring.replace(""+ch, "");
String before = EMPTY_SPACE+TAB+"word"+TAB+EMPTY_SPACE
Where
EMPTY_SPACE = " " (this is String)
TAB = '\t' (this is Character)
String after = before.replaceAll(" ", "").replace('\t', '\0')
means
after = "word"
You can only re-use an existing character. e.g. \0 If you put this in a String, you will have a String with one character in it.
Say you want a char such that when you do
String s =
char ch = ?
String s2 = s + ch; // there is not char which does this.
assert s.equals(s2);
what you have to do instead is
String s =
char ch = MY_NULL_CHAR;
String s2 = ch == MY_NULL_CHAR ? s : s + ch;
assert s.equals(s2);
Use the \b operator (the backspace escape operator) in the second parameter
String test= "Anna Banana";
System.out.println(test); //returns Anna Banana<br><br>
System.out.println(test.replaceAll(" ","\b")); //returns AnnaBanana removing all the spaces in the string

Categories