How do I simply convert a UTF-16 character to String?
something Like
String str = TheMagicalFunction(0x25E6);
You can use Character.toString(char):
String str = Character.toString((char) 0x25E6);
You can omit the cast when first storing the character in a variable …
char whiteBullet = 0x25E6;
String whiteBulletString = Character.toString(whiteBullet);
… or when using a Unicode escape which in this case is easy since the character belongs to the Basic Multilingual Plane (BMP):
String str = Character.toString('\u25E6');
The method String.valueOf(char) is equivalent and/but has multiple overloads. Beware of this:
String str = String.valueOf(0x25E6); // "9702" (decimal value)
String str2 = String.valueOf((char) 0x25E6); // "◦"
String str3 = String.valueOf('\u25E6'); // "◦"
You need to:
If the character is an integer, cast it to char.
Put it in a 1-element char[].
Pass it the the String constructor.
So,
String str = new String(new char[] {(char) 0x25E6});
Related
I am trying to replace only one character of a string. But whenever the character has multiple occurrences within the string, all of those characters are being replaced, while I only want the particular character to be replaced. For example:
String str = "hello world";
str = str.replace(str.charAt(2), Character.toUpperCase(str.charAt(2)));
System.out.println(str);
Gives the result:
heLLo worLd
while I want it to be:
heLlo world
What can I do to achieve this?
replace will not work because it replace all the occurrence in the string. Also replaceFirst will not work as it will always remove
the first occurrence.
As Strings are non mutable , so in either way you need create a new string always. Can be done by either of the following.
Use substring, and manually create the string that you want.
int place = 2;
str = str.substring(0,place)+Character.toUpperCase(str.charAt(place))+str.substring(place+1);
Convert the string to array of characters and replace any character that you want by using index, and then convert array back to the string.
You should use a StringBuilder instead of String to achieve this goal.
This code works too
String str = "hello world";
str = str.replaceFirst(String.valueOf(str.charAt(2)),
String.valueOf(Character.toUpperCase(str.charAt(2))));
System.out.println(str);
String str = "hello world";
char[] charArray = str.toCharArray();
charArray[2] = Character.toUpperCase(charArray[2]);
str = new String(charArray);
System.out.println(str);
replace(char, char) will replace all occurrences of the specified char, not only the char at the index. From the documentation
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
You can do something like
String str = "hello world";
String newStr = str.substring(0, 2) + Character.toUpperCase(str.charAt(2)) + str.substring(3);
How can I separate the arbitrary characters from a string object in java? For example consider the following code and I want to separate arbitrary characters from that.
String string = "My String";.
in the above code, I want to get the t character from string object and then assign it in the subString object like the following :
String subString = "t";
Use string.charAt(index).It is used to select the characters in the original string with the specified index.
String string = "My String";
char c = string.charAt(4);
System.out.println(c);
Output: t
This is an interview question. I was thinking of a solution in java. This questions seems very simple, is there a catch here?
I was thinking of the following solution:
string1 + 1*hash(String1) + string2 + 2*hash(String2).
If I concat strings like this, then I can decode them as well easily into 2 separate strings.
Am I missing something in the question?
Encode:
String encoded = new JsonArray().add(str1).add(str2).toString();
Decode:
JsonArray arr = JsonArray.readFrom(encoded);
String str1 = arr.get(0).asString();
String str2 = arr.get(1).asString();
Here I use minimal-json lib, but it's pretty similar with any other JSON library as well.
Note that it's usually a bad idea to invent new formats of encoding the information into the string as you have plenty of existing ones (xml, json, yaml, etc.) which already solved all the possible issues like symbol escaping and exception handling.
To encode:
String encoded = ""+str1.length()+"/"+str1+str2;
To decode:
String[] temp = encoded.split("/", 2);
int length1 = Integer.parseInt(temp[0]);
String str1 = temp[1].substring(0, length1);
String str2 = temp[1].substring(length1);
Explanation:
The encoded string is in the form "<number>/<str1><str2>". When you call split(regex, limit) the size of the resulting array will be at most limit, considering only the first matches of regex. Thus even if your strings contain the character / you can be sure that the resulting array will be {"<number>", "<str1><str2>"}.
the substring(begin, end) return a string starting at begin inclusive and ending at end exclusive, giving you a resulting substring of end-begin length. Since you are calling it with values(0, str1.length()) what you get is exactly str1. The last call will return a substring from str1.length(), which is also the index of the first character of str2, to the end of the string (which is the end of str2).
Reference: String javadoc page
One way is to use the length of the first string.
// encode
String concat = string1 + string2;
// decode
String str1 = concat.substring( 0, string1.length() );
String str2 = concat.substring( string1.length(), concat.length() );
Another way is to use a delimiter. But the delimiter character should not be included in any of the strings to be joined.
// encode
String concat = "hello" + "`" + "world!";
// decode
String[] decoded = concat.split("`");
String str1 = decoded[0];
String str2 = decoded[1];
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]);
I know of no easy way to do this. Suppose I have the following string-
"abcdefgh"
I want to get a string by replacing the third character 'c' with 'x'.
The long way out is this -
s1 = substring before third character = "ab" in this case
s2 = new character = "x" in this case
s3 = substring after third character = "defgh" in this case
finalString = s1 + s2 + s3
Is there a simpler way? There should be some function like
public String replace(int pos, char replacement)
Use StringBuilder#replace().
StringBuilder sb = new StringBuilder("abcdefgh");
sb.replace(2, 3, "x");
String output = sb.toString();
http://ideone.com/Tg5ut
You can convert the String to a char[] and then replace the character. Then convert the char[] back to a String.
String s = "asdf";
char[] arr = s.toCharArray();
arr[0] = 'b';
s = new String(arr);
No. There is no simpler way than to concatenate the pieces.
Try using a StringBuilder instead StringBuilder Java Page
Since every String is basically just a char[] anyway, you could just grab it and manipulate the individual chars that way.
Try the String.replace(Char oldChar, Char newChar) method or use a StringBuilder
How about:
String crap = "crap";
String replaced = crap.replace(crap.charAt(index), newchar);
but this will replace all instances of that character
String yourString = "abcdef"
String newString = yourString.replaceAll("c" , "x");
System.out.println("This is the replaced String: " + newString);
This is the replaced String: abxdef