How do you convert a char array to a string array? Or better yet, can you take a string and convert it to a string array that contains each character of the string?
Edit: thanks #Emiam! Used his code as a temp array then used another array to get rid of the extra space and it works perfectly:
String[] tempStrings = Ext.split("");
String[] mStrings = new String[Ext.length()];
for (int i = 0; i < Ext.length(); i++)
mStrings[i] = tempStrings[i + 1];
Or better yet, can you take a string and convert it to a string array
that contains each character of the string?
I think this can be done by splitting the string at "". Like this:
String [] myarray = mystring.split("");
Edit:
In case you don't want the leading empty string, you would use the regex: "(?!^)"
String [] mySecondArray = mystring.split("(?!^)");
Beautiful Java 8 one-liner for people in the future:
String[] array = Stream.of(charArray).map(String::valueOf).toArray(String[]::new);
I have made the following test to check Emiam's assumption:
public static void main(String[] args) {
String str = "abcdef";
String [] array = str.split("");
}
It works, but it adds an empty string in position 0 of the array.
So array is 7 characters long and is { "", "a", "b", "c", "d", "e", "f" }.
I have made this test with Java SE 1.6.
brute force:
String input = "yourstring";
int len = input.length();
String [] result = new String[len];
for(int i = 0; i < len ; i ++ ){
result[i] = input.substring(i,i+1);
}
This will give string[] as result, but will have only one value as below
String[] str = {"abcdef"};
// char[] to String[]
String[] sa1 = String.valueOf(cArray).split("");
Related
I am required to write up a static method named getSuccessiveLetters(words) that takes a string array and returns a single String. If the String array is {"hello", "world"}, then the program should return "ho". "h" is from the first word, "o" is the 2nd letter from the 2nd word and so on.
I managed to get the correct return value for {"hello", "world"}, but if the String array contains, for example,{"1st", "2nd", "3rd", "4th", "fifth"} it goes out of range it struggles.
public class Template01 {
public static void main(String[] args) {
System.out.println(getSuccessiveLetters(new String[]{"1st", "2nd", "3rd", "4th", "fifth"}));
}
public static String getSuccessiveLetters(String[] words) {
char Str[] = new char[words.length];
String successive;
for(int i = 0; i < words.length; i++){
successive = words[i];
if (i < successive.length()){
Str[i] = successive.charAt(i);
}
else
{
break;
}
}
successive = new String(Str);
return successive;
}
I expected the return value to be 1nd, but the actual output is 1nd\x00\x00.
This is happening because when you initialize a char array, it fills the array with the default char value.
You can use StringBuilder or List<Character> to grow your "array" with each addition.
Change
char[] str = new char[words.length];
to
StringBuilder str = new StringBuilder();
and
str[i] = successive.charAt(i);
to
str.append(successive.charAt(i));
and then at the end successive = str.toString();.
This is because when you ignore the strings in the original array that are not long enough, you are not setting some of the char array elements as a result. This means that some elements will have the char value of \0 (default value of char). The resulting string therefore has these extra \0 characters as well.
I think it is more suitable to use a StringBuilder rather than a char[] here:
public static String getSuccessiveLetters(String[] words) {
StringBuilder builder = new StringBuilder();
String successive;
for(int i = 0; i < words.length; i++){
successive = words[i];
if (i < successive.length()){
builder.append(successive.charAt(i));
}
// you should not break here, because there might be a longer string in the array later on.
// but apparently you don't want the "h" in "fifth"? Then I guess you should break here.
}
successive = builder.toString();
return successive;
}
I recommend using Unit-Tests here. This could help you to improve.
you are creating a charArray here:
char Str[] = new char[words.length];
this array has the length of your string-array
new String[]{"1st", "2nd", "3rd", "4th", "fifth"}
which is 5
you create 3 entries for your new array (because you break at the first word, which is too short)
therefor you get 3 letters "1nd" and the 2 other slots in your array are filled with blanks when calling
successive = new String(Str);
1st: think about the break statement
2nd: think about using a StringBuilder / StringBuffer instead of a char[] for your matches
imho the most correct result should be 1nd h - but this depends on your given task
Hello i have a little problem with array conversion
i want to convert this array format ["x","z","y"] To this String Format ('x','y','z') with commas and parentheses.
btw this array is dynamic in size may be increased or decreased
this is my try
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
String [] arr = {"x","y","z"};
String s = "(";
for(int i = 0; i <arr.length;i++){
s +="'".concat(arr[i]).concat("'") + ',' ;
if(i == arr.length-1)
s.replace(',', ')');
}
System.out.print(s);
}
this is my output ('x','y','z',
i want to replace the last comma with ')'
This also will do the magic..
Please use StringBuilder for these kind of string operations..
for (int i = 0; i < arr.length; i++) {
s += "'".concat(arr[i]).concat("'") + ',';
}
s = s.concat(")");
System.out.print(s.replace(",)", ")"));
s.replace(',', ')');
Here you are trying to replace the comma, but Strings in java are immutable, it means you are in fact replacing this, but not assigning the value to any variable, so it's pointless. Also, that replace will not do what you think. Instead, you need to:
s = s.substring(0, s.length()-1);
This is gonna remove the last character from the String (that is extra comma at the end). Then just append ) to it and you are done.
You can also use the String.join method :
public static void main(String[] args) {
String [] arr = {"x","y","z"};
String s = String.join("','", arr);
s = "('"+s+"')";
System.out.print(s);
}
You can try this, using String.format and String.join
String[] arr = { "x", "y", "z" };
String s = String.format("('%s')", String.join("','", arr));
System.out.println(s);
It print
('x','y','z')
Edit
If you are using jdk7, you can use StringBuilder to avoid performance issues, as shown in the code:
String[] a = { "x", "y", "z" };
StringBuilder b = new StringBuilder("(");
for (int i = 0; i < a.length; i++) {
b.append("'").append(String.valueOf(a[i])).append("'");
b.append((i == a.length - 1) ? ")" : ", ");
}
System.out.println(b);
It print
('x','y','z')
I want to write code that splits a string into separate substrings each with 3 characters
and assign them to a string array for example the string "abcdefg" can be spit to "abc", "bcd", "cde", "efg" and these are assigned to a string array. I have the following code which is getting an error:
String[] words = new String[] {};
String sequence = "abcdefg";
int i;
for(i = 0; i <= sequence.length()-3; i++) {
words[i] = sequence.substring(i, 3+i);
System.out.println(words[i]);
}
String[] words=new String[] {}; // empty array
you have empty array.
words[i] // when i=0
there is no index in empty array match with 0th index.
Solution.
You can define the size of array at the moment you are define the array. The best way is get the length from sequence
String sequence="abcdefg";
String[] words=new String[sequence.length()];
Use the following code instead:
String sequence="abcdefg";
String[] words=new String[sequence.length()-2];
int i;
for(i=0;i<=(sequence.length()-3);i++){
words[i]=sequence.substring(i,3+i);
System.out.println(words[i]);
}
Or you could use arraylist of strings
You could get the length from the sequence string divided by the number of characters you want to store in order to know how big should your array be. For instance
String sequence="abcdefg";
int myLength = sequence.length/3;
String[] words=new String[myLength];
And then you could use that length to populate the array
for(i=0;i<=myLength;i++){
words[i]=sequence.substring(i,3+i);
System.out.println(words[i]);
}
I have a string, actually user put in console next string :
10 20 30 40 50
how i can parse it to int[] ?
I tried to use Integer.parseInt(String s); and parse string with String.indexOf(char c) but i think it's too awful solution.
You could use a Scanner and .nextInt(), or you could use the .split() command on the String to split it into an array of Strings and parse them separately.
For example:
Scanner scanner = new Scanner(yourString);
ArrayList<Integer> myInts = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
myInts.add(scanner.nextInt());
}
For the split:
String[] intParts = yourString.split("\\s+");
ArrayList<Integer> myInts = new ArrayList<Integer>();
for (String intPart : intParts) {
myInts.add(Integer.parseInt(intPart));
}
Split the String, using the String#split() method with the delimiter space.
For each element in the String[], parse it into an int using Integer.parseInt() and add them to your int[].
String split[] = string.split(" ")
is will generate an array of string then you can parse the array to int.
Split the string then parse the integers like the following function:
int[] parseInts(String s){
String[] sNums = s.split(" ");
int[] nums = new int[sNums.length];
for(int i = 0; i < sNums.length; i++){
nums[i] = Integer.parseInt(sNums[i);
}
return nums;
}
Let's say I have this String -
string = "AEIOU";
and I wanted to convert it to an ArrayList<String>, where each character is it's own individual String within the ArrayList<String>
[A, E, I, O, U]
EDIT: I do NOT want to convert to ArrayList<Character> (yes, that's very straightforward and I do pay attention in class), but I DO want to convert to an ArrayList<String>.
How would I do that?
transform the String into a char array,
char[] cArray = "AEIOU".toCharArray();
and while you iterate over the array, transform each char into a String, and then add it to the list,
List<String> list = new ArrayList<String>(cArray.length);
for(char c : cArray){
list.add(String.valueOf(c));
}
Loop and use String.charAt(i), to build the new list.
You can do it by using the split method and setting the delimiter as an empty string like this:
ArrayList<String> strings = new ArrayList<>(Arrays.asList(string.split("")));
First you have to define the arrayList and then iterate over the string and create a variable to hold the char at each point within the string. then you just use the add command. You will have to import the arraylist utility though.
String string = "AEIOU";
ArrayList<char> arrayList = new ArrayList<char>();
for (int i = 0; i < string.length; i++)
{
char c = string.charAt(i);
arrayList.add(c);
}
The import statement looks like : import java.util.ArrayList;
To set it as a string arrayList all you have to do is convert the char variables we gave you and convert it back to a string then add it: (And import the above statement)
ArrayList<String> arrayList = new ArrayList<String>();
String string = "AEIOU"
for (int i = 0; i < string.length; i++)
{
char c = string.charAt(i);
String answer = Character.toString(c);
arrayList.add(answer);
}
Since everyone is into doing homework this evening ...
String myString = "AEIOU";
List<String> myList = new ArrayList<String>(myString.length());
for (int i = 0; i < myString.length(); i++) {
myList.add(String.valueOf(myString.charAt(i)));
}
For a single line answer use the following code :
Arrays.asList(string .toCharArray());
Kotlin approach:
fun String.toArrayList(): ArrayList<String> {
return ArrayList(this.split("").drop(1).dropLast(1))
}
var letterArray = "abcd".toArrayList()
print(letterArray) // arrayListOf("a", "b", "c", "d")