Why isn't the following code working ?
String s = "fecbda";
Arrays.sort(s.toCharArray());
System.out.println(s);
Strings are immutable so you can't change them, and you shouldn't expect this to do anything.
What you might have intended is
String s = "fecbda";
char[] chars = s.toCharArray();
Arrays.sort(chars);
String s2 = new String(chars);
System.out.println(s2);
It does not work as s.toCharArray():
Returns:
a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string.
The operative part of the documentation is that it creates a new array (i.e. a copy of the characters in the string) and when you sort that array you do not sort the String.
You cannot sort the string as it is immutable but you can make a new string out of the sorted character array like this:
String s = "fecbda";
char[] c = s.toCharArray();
Array.sort( c );
String n = new String( c );
As an alternative method, you can do it in Java 8 using streams:
String s = "fecbda";
String n = s.chars() // Convert to an IntStream of character codes
.sorted() // Sort
.mapToObj(i -> Character.toString((char) i)) // Convert to strings
.collect(Collectors.joining()); // Concatenate the strings.
Related
So i have an array of strings. Each index contains a string like "abc" "fnsb" "feros". I want to pass in this array of strings through a for loop that can get each character's ASCII value of ALL the strings listed above and possibly store each string's character's ASCII value in another array. For example, if my array of strings has
mystrings[0] = hi
mystrings[1] = hello
mystrings[2] = farewell
I want it to take the ASCII values of "h" and "i" and store it in an newarray[0], then take the ASCII values of "h","e","l","l","o" and store it into newarray[1], and ETC.
Note: Above is a bunch of pseudocode. Here is what I actually have:
String[] mystrings= new String[100];
double [] newarray = new double[100];
for (int x=0; x<100; x++){
char character = mystrings[x].charAt(x);
int ascii = (int) character;
newarray[x] = ascii;
System.out.println(newarray[x]);
}
Another note: There are indeed multiple strings stored in each index of the mystrings array. It's just in another part of my code that I don't want to share. So please assume that the "mystrings" array is properly filled with various strings. Thank you!
The key issue in your pseudocode is that the result must be not simply an array, but an array of arrays:
int[][] newarray = new int[mystrings.length][];
The second issue is that getting character codes must be done in a separate loop, nested inside the first one. The loop must go from zero to mystring[i].length():
char character = mystrings[x].charAt(y);
// ^
Note that charAt parameter is not the same as x in mystrings[x], because it needs to be a separate loop.
String s = "hello";
byte[] bytes = s.getBytes("US-ASCII");
Here's a Java 8 solution:
String[] mystrings = {"hi", "bye"};
List<List<Integer>> result;
result = Arrays.stream(mystrings)
.map(s -> s.chars()
.mapToObj(e -> (char) e)
.collect(Collectors.toList()))
.map(chars -> chars.stream()
.map(Integer::new)
.collect(Collectors.toList())
)
.collect(Collectors.toList());
... and the output would be:
[[104, 105], [98, 121, 101]]
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});
I have a Character array (not char array) and I want to convert it into a string by combining all the Characters in the array.
I have tried the following for a given Character[] a:
String s = new String(a) //given that a is a Character array
But this does not work since a is not a char array. I would appreciate any help.
Character[] a = ...
new String(ArrayUtils.toPrimitive(a));
ArrayUtils is part of Apache Commons Lang.
The most efficient way to do it is most likely this:
Character[] chars = ...
StringBuilder sb = new StringBuilder(chars.length);
for (Character c : chars)
sb.append(c.charValue());
String str = sb.toString();
Notes:
Using a StringBuilder avoids creating multiple intermediate strings.
Providing the initial size avoids reallocations.
Using charValue() avoids calling Character.toString() ...
However, I'd probably go with #Torious's elegant answer unless performance was a significant issue.
Incidentally, the JLS says that the compiler is permitted to optimize String concatenation expressions using equivalent StringBuilder code ... but it does not sanction that optimization across multiple statements. Therefore something like this:
String s = ""
for (Character c : chars) {
s += c;
}
is likely to do lots of separate concatenations, creating (and discarding) lots of intermediate strings.
Iterate and concatenate approach:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
StringBuilder builder = new StringBuilder();
for (Character c : chars)
builder.append(c);
System.out.println(builder.toString());
Output:
abc
First convert the Character[] to char[], and use String.valueOf(char[]) to get the String as below:
char[] a1 = new char[a.length];
for(int i=0; i<a.length; i++) {
a1[i] = a[i].charValue();
}
String text = String.valueOf(a1);
System.out.println(text);
It's probably slow, but for kicks here is an ugly one-liner that is different than the other approaches -
Arrays.toString(characterArray).replaceAll(", ", "").substring(1, characterArray.length + 1);
Probably an overkill, but on Java 8 you could do this:
Character[] chars = {new Character('a'),new Character('b'),new Character('c')};
String value = Arrays.stream(chars)
.map(Object::toString)
.collect( Collectors.joining() );
At each index, call the toString method, and concatenate the result to your String s.
how about creating your own method that iterates through the list of Character array then appending each value to your new string.
Something like this.
public String convertToString(Character[] s) {
String value;
if (s == null) {
return null;
}
Int length = s.length();
for (int i = 0; i < length; i++) {
value += s[i];
}
return value;
}
Actually, if you have Guava, you can use Chars.toArray() to produce char[] then simply send that result to String.valueOf().
int length = cArray.length;
String val="";
for (int i = 0; i < length; i++)
val += cArray[i];
System.out.println("String:\t"+val);
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
I have a string = "name";
I want to convert into a string array.
How do I do it?
Is there any java built in function? Manually I can do it but I'm searching for a java built in function.
I want an array where each character of the string will be a string.
like char 'n' will be now string "n" stored in an array.
To start you off on your assignment, String.split splits strings on a regular expression and this expression may be an empty string:
String[] ary = "abc".split("");
Yields the array:
(java.lang.String[]) [, a, b, c]
Getting rid of the empty 1st entry is left as an exercise for the reader :-)
Note: In Java 8, the empty first element is no longer included.
String strName = "name";
String[] strArray = new String[] {strName};
System.out.println(strArray[0]); //prints "name"
The second line allocates a String array with the length of 1. Note that you don't need to specify a length yourself, such as:
String[] strArray = new String[1];
instead, the length is determined by the number of elements in the initalizer. Using
String[] strArray = new String[] {strName, "name1", "name2"};
creates an array with a length of 3.
I guess there is simply no need for it, as it won't get more simple than
String[] array = {"name"};
Of course if you insist, you could write:
static String[] convert(String... array) {
return array;
}
String[] array = convert("name","age","hobby");
[Edit]
If you want single-letter Strings, you can use:
String[] s = "name".split("");
Unfortunately s[0] will be empty, but after this the letters n,a,m,e will follow. If this is a problem, you can use e.g. System.arrayCopy in order to get rid of the first array entry.
Assuming you really want an array of single-character strings (not a char[] or Character[])
1. Using a regex:
public static String[] singleChars(String s) {
return s.split("(?!^)");
}
The zero width negative lookahead prevents the pattern matching at the start of the input, so you don't get a leading empty string.
2. Using Guava:
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
import com.google.common.base.Functions;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
// ...
public static String[] singleChars(String s) {
return
Lists.transform(Chars.asList(s.toCharArray()),
Functions.toStringFunction())
.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
In java 8, there is a method with which you can do this: toCharArray():
String k = "abcdef";
char[] x = k.toCharArray();
This results to the following array:
[a,b,c,d,e,f]
String data = "abc";
String[] arr = explode(data);
public String[] explode(String s) {
String[] arr = new String[s.length];
for(int i = 0; i < s.length; i++)
{
arr[i] = String.valueOf(s.charAt(i));
}
return arr;
}
Simply use the .toCharArray() method in Java:
String k = "abc";
char[] alpha = k.toCharArray();
This should work just fine in Java 8.
String array = array of characters ?
Or do you have a string with multiple words each of which should be an array element ?
String[] array = yourString.split(wordSeparator);
Convert it to type Char?
http://www.javadb.com/convert-string-to-character-array
You could use string.chars().mapToObj(e -> new String(new char[] {e}));, though this is quite lengthy and only works with java 8. Here are a few more methods:
string.split(""); (Has an extra whitespace character at the beginning of the array if used before Java 8)
string.split("|");
string.split("(?!^)");
Arrays.toString(string.toCharArray()).substring(1, string.length() * 3 + 1).split(", ");
The last one is just unnecessarily long, it's just for fun!
An additional method:
As was already mentioned, you could convert the original String "name" to a char array quite easily:
String originalString = "name";
char[] charArray = originalString.toCharArray();
To continue this train of thought, you could then convert the char array to a String array:
String[] stringArray = new String[charArray.length];
for (int i = 0; i < charArray.length; i++){
stringArray[i] = String.valueOf(charArray[i]);
}
At this point, your stringArray will be filled with the original values from your original string "name".
For example, now calling
System.out.println(stringArray[0]);
Will return the value "n" (as a String) in this case.
here is have convert simple string to string array using split method.
String [] stringArray="My Name is ABC".split(" ");
Output
stringArray[0]="My";
stringArray[1]="Name";
stringArray[2]="is";
stringArray[3]="ABC";
Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).
import org.apache.commons.lang3.StringUtils;
StringUtils.split(null) => null
StringUtils.split("") => []
StringUtils.split("abc def") => ["abc", "def"]
StringUtils.split("abc def") => ["abc", "def"]
StringUtils.split(" abc ") => ["abc"]
Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:
import com.google.common.base.Splitter;
Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();
SPLITTER.split("a,b, c , , ,, ") => [a, b, c]
SPLITTER.split("") => []
SPLITTER.split(" ") => []
SPLITTER.split(null) => NullPointerException
If you want a list rather than an iterator then use Splitter.splitToList().
/**
* <pre>
* MyUtils.splitString2SingleAlphaArray(null, "") = null
* MyUtils.splitString2SingleAlphaArray("momdad", "") = [m,o,m,d,a,d]
* </pre>
* #param str the String to parse, may be null
* #return an array of parsed Strings, {#code null} if null String input
*/
public static String[] splitString2SingleAlphaArray(String s){
if (s == null )
return null;
char[] c = s.toCharArray();
String[] sArray = new String[c.length];
for (int i = 0; i < c.length; i++) {
sArray[i] = String.valueOf(c[i]);
}
return sArray;
}
Method String.split will generate empty 1st, you have to remove it from the array. It's boring.
Based on the title of this question, I came here wanting to convert a String into an array of substrings divided by some delimiter. I will add that answer here for others who may have the same question.
This makes an array of words by splitting the string at every space:
String str = "string to string array conversion in java";
String delimiter = " ";
String strArray[] = str.split(delimiter);
This creates the following array:
// [string, to, string, array, conversion, in, java]
Source
Tested in Java 8