Home > front end >  convert String to Array JAVA
convert String to Array JAVA

Time:07-20

I have a string String myStringArray = "[491174, 414529, 414557]";. I want output 491174, 414529, 414557 just this part. I try many many methods to convert string to array and many other things. I tried something I'm adding the code below.

My Code

String myStringArray = "[491174, 414529, 414557]";
String newArray = myStringArray.replaceAll(" ", "");
System.out.println("Before Remove : "   newArray);

String remove = newArray.replaceAll("[^a-zA-Z0-9]", ",");
String rm = remove.replaceFirst(",", "");

System.out.println("After Remove : "   rm);

Output

Before Remove : [491174,414529,414557]
After Remove : 491174,414529,414557,

As you can see I have , in the end and I don't know how to remove this ,. Please help me if you can.

CodePudding user response:

You can

Using str.split() method
Using loops
Using Set.toArray() method
Using String tokenizer
Using pattern.split() method

String str = "Geeks for Geeks";
String strArray[] = str.split(" ");
System.out.println("String : "   str);
System.out.println("String array : [ ");
 
// Iterating over the string
for (int i = 0; i < strArray.length; i  ) {
// Printing the elements of String array
   System.out.print(strArray[i]   ", ");
}
System.out.print("]");
    

CodePudding user response:

rm = rm.substring(0, rm.length() - 1);
  • Related