Java: String to integer array - java

I have a string, which is a list of coordinates, as follows:
st = "((1,2),(2,3),(3,4),(4,5),(2,3))"
I want this to be converted to an array of coordinates,
a[0] = 1,2
a[1] = 2,3
a[2] = 3,4
....
and so on.
I can do it in Python, but I want to do it in Java.
So how can I split the string into array in java??

It can be done fairly easily with regex, capturing (\d+,\d+) and the looping over the matches
String st = "((1,2),(2,3),(3,4),(4,5),(2,3))";
Pattern p = Pattern.compile("\\((\\d+),(\\d+)\\)");
Matcher m = p.matcher(st);
List<String> matches = new ArrayList<>();
while (m.find()) {
matches.add(m.group(1) + "," + m.group(2));
}
System.out.println(matches);
If you genuinely need an array, this can be converted
String [] array = matches.toArray(new String[matches.size()]);

Alternative solution:
String str="((1,2),(2,3),(3,4),(4,5),(2,3))";
ArrayList<String> arry=new ArrayList<String>();
for (int x=0; x<=str.length()-1;x++)
{
if (str.charAt(x)!='(' && str.charAt(x)!=')' && str.charAt(x)!=',')
{
arry.add(str.substring(x, x+3));
x=x+2;
}
}
for (String valInArry: arry)
{
System.out.println(valInArry);
}
If you don't want to use Pattern-Matcher;

This should be it:
String st = "((1,2),(2,3),(3,4),(4,5),(2,3))";
String[] array = st.substring(2, st.length() - 2).split("\\),\\(");

Related

Remove and get text, from comma separated string if it has # as prefix in java?

I have a string in java as
Input
String str = "1,2,3,11,#5,#7,9";
Output Desired
String result = "1,2,3,11,9";
// And 5,7 with special character # in separate Array-list
//List<String> list = ["5","7"];
Note: This special character # is dynamic, it may or may not be present in string.
I know how to remove # using str.replaceAll("#", "");, but how to get 5 and 7 in a separate list.
String str = "1,2,3,11,#5,#7,9";
List<String> parts = Arrays.asList(str.split(","));
List<Integer> normalNumbers = parts.stream().filter(i -> !i.startsWith("#")).map(Integer::parseInt).collect(
Collectors.toList());
List<Integer> specialNumbers = parts.stream().filter(i -> i.startsWith("#")).map(i -> Integer.valueOf(i.substring(1))).collect(Collectors.toList());
System.out.println(normalNumbers);
System.out.println(specialNumbers);
String in Java has a method called split(). You could easily use this to get all Integers with & without the prefix #
String str = "1,2,3,11,#5,#7,9";
List<Integer> res = Arrays.asList(str.split(",")).stream().map(ch->{
if(!ch.startsWith("#")){
return Integer.parseInt(ch);
}else {
return null;
}
}).filter(Objects::nonNull).collect(Collectors.toList());
System.out.println(res);
1. You could try String.split(),
String[] tokens = str.split(",");
2. Create 2 new String Array-List,
ArrayList<String> num = new ArrayList<String>();
ArrayList<String> result = new ArrayList<String>();
3. Then loop thru the tokens, checking each token, then push,
for(int i = 0; i < tokens.length; i++)
{
if(tokens[i].charAt(0) == '#')
num.add(String.valueOf(tokens[i].charAt(1)));
else
result.add(tokens[i]);
}
String str = "1,2,3,11,#5,#7,9";
List<String> s = Arrays.asList(str.split(",")).stream().filter(a->a.startsWith("#")).map(a->a.replace("#", "")).collect(Collectors.toList());
System.out.println(s); //Output [5, 7]
str = Arrays.asList(str.split(",")).stream().filter(a->!a.startsWith("#")).collect(Collectors.joining(","));
System.out.println(str); //Output 1,2,3,11,9

Substring first, second, third, ... , n match

Given: String s = "{aaa}{bbb}ccc.
How to get an array (or list) which elements will be:
0th element: aaa
1st element: bbb
2nd element: ccc
This is my try:
String x = "{aaa}{b}c";
return Arrays.stream(x.split("\\}"))
.map(ss -> {
Pattern pattern = Pattern.compile("\\w*");
Matcher matcher = pattern.matcher(ss);
matcher.find();
return matcher.group();
})
.toArray(String[]::new);
(assume only Java <= 8 allowed)
A simple replace should be enough if your strings are well formed like your examples:
String[] myStrings = {"{aaa}bbb", "{aaa}{bbb}{ccc}ddd", "{aaa}{bbb}{ccc}{ddd}eee"};
for(String str : myStrings){
String[] splited = str.replace("}{", "}").replace("{", "").split("}");
System.out.println(Arrays.toString(splited));
}
prints:
[aaa, bbb]
[aaa, bbb, ccc, ddd]
[aaa, bbb, ccc, ddd, eee]
private static List<String> parse ()
{
String x = "{aaa}{b}c";
Pattern pattern = Pattern.compile ("[^{\\}]+(?=})");
List < String > allMatches = new ArrayList < String > ();
Matcher m = pattern.matcher (x);
while (m.find ())
{
allMatches.add (m.group ());
}
String lastPart = x.substring(x.lastIndexOf("}")+1);
allMatches.add(lastPart);
System.out.println (allMatches);
return allMatches
}
Make sure you do a check for lastIndexOf >-1, if your string may or may not contain last part without braces.
This way is a bit simpler than using regex (and may be a bit faster too):
String[] strings = new String[100];
int index = 0;
int last = 0;
for(int i = 1; i < s.length(); i++){
if(s.charAt(i) == "}"){
strings[index++] = s.substring(last + 1, i - 1);
last = i + 1;
}
}
strings[index++] = s.substring(last, s.length());
If you want to use regex, the pattern needs to identify sequences of one or more letters, you can try the pattern (?:{([a-z]+)})*([a-z]+).

Java, How to split String with shifting

How can I split a string by 2 characters with shifting.
For example;
My string is = todayiscold
My target is: "to","od","da","ay","yi","is","sc","co","ol","ld"
but with this code:
Arrays.toString("todayiscold".split("(?<=\\G.{2})")));
I get: `"to","da","yi","co","ld"
anybody helps?
Try this:
String e = "example";
for (int i = 0; i < e.length() - 1; i++) {
System.out.println(e.substring(i, i+2));
}
Use a loop:
String test = "abcdefgh";
List<String> list = new ArrayList<String>();
for(int i = 0; i < test.length() - 1; i++)
{
list.add(test.substring(i, i + 2));
}
Following regex based code should work:
String str = "todayiscold";
Pattern p = Pattern.compile("(?<=\\G..)");
Matcher m = p.matcher(str);
int start = 0;
List<String> matches = new ArrayList<String>();
while (m.find(start)) {
matches.add(str.substring(m.end()-2, m.end()));
start = m.end()-1;
}
System.out.println("Matches => " + matches);
Trick is to use end()-1 from last match in the find() method.
Output:
Matches => [to, od, da, ay, yi, is, sc, co, ol, ld]
You cant use split in this case because all split does is find place to split and brake your string in this place, so you cant make same character appear in two parts.
Instead you can use Pattern/Matcher mechanisms like
String test = "todayiscold";
List<String> list = new ArrayList<String>();
Pattern p = Pattern.compile("(?=(..))");
Matcher m = p.matcher(test);
while(m.find())
list.add(m.group(1));
or even better iterate over your Atring characters and create substrings like in D-Rock's answer

how to get the value after certain Prefix in android?

I have a string like abc-5,xyz-9,pqr-15 Now,I want to get the value only after "-" So, how can i get that value..and i want this value in String Array?
You can try
String string = "abc-5,xyz-9,pqr-15";
String[] parts = string.split(",");
String val1 = parts[0].split("-");
.....
and so on
int pos = string.indexOf('-');
String sub = string.substring(pos);
If you have multiple values in each string, you'll have to split it first (using split method). For example:
String[] array = string.split(',');
String[] values = new String[array.length];
for(int i = 0; i < array.length; i++)
values[i] = array[i].substring(arrays[i].indexOf('-'));
Now you have the values in an array.
I would use split on your string.
String str = "abc-5,xyz-9,pqr-15";
String[] arr = str.split(",");
for (String elem: arr) {
System.out.print(elem.split("-")[1] + " : "); // Will print - `5 : 9 : 15`
}
or with Regular Expression like this: -
Matcher matcher = Pattern.compile("-(\\d+)").matcher(str);
while(matcher.find()) {
System.out.println(matcher.group(1));
}
Use:
String newString= oldString.substring(oldString.indexOf('-'));

How to get list of Integer from String

my string contains Integer separated by space:
String number = "1 2 3 4 5 "
How I can get list of Integer from this string ?
You can use a Scanner to read the string one integer at a time.
Scanner scanner = new Scanner(number);
List<Integer> list = new ArrayList<Integer>();
while (scanner.hasNextInt()) {
list.add(scanner.nextInt());
}
ArrayList<Integer> lst = new ArrayList<Integer>();
for (String field : number.split(" +"))
lst.add(Integer.parseInt(field));
With Java 8+:
List<Integer> lst =
Arrays.stream(number.split(" +")).map(Integer::parseInt).collect(Collectors.toList());
String number = "1 2 3 4 5";
String[] s = number.split("\\s+");
And then add it to your list by using Integer.parseInt(s[index]);
List<Integer> myList = new List<Integer>();
for(int index = 0 ; index<5 ; index++)
myList.add(Integer.parseInt(s[index]);
In Java 8 you can use streams and obtain the conversion in a more compact way:
String number = "1 2 3 4 5 ";
List<Integer> x = Arrays.stream(number.split("\\s"))
.map(Integer::parseInt)
.collect(Collectors.toList());
Using Java8 Stream API map and mapToInt function you can archive this easily:
String number = "1 2 3 4 5";
List<Integer> x = Arrays.stream(number.split("\\s"))
.map(Integer::parseInt)
.collect(Collectors.toList());
or
String stringNum = "1 2 3 4 5 6 7 8 9 0";
List<Integer> poolList = Arrays.stream(stringNum.split("\\s"))
.mapToInt(Integer::parseInt)
.boxed()
.collect(Collectors.toList());
Firstly,using split() method to make the String into String array.
Secondly,using getInteger() method to convert String to Integer.
String number="1 2 3 4 5";
List<Integer> l=new ArrayList<Integer>();
String[] ss=number.split(" ");
for(int i=0;i<ss.length;i++)
{
l.add(Integer.parseInt(ss[i]));
}
System.out.println(l);
Simple solution just using arrays:
// variables
String nums = "1 2 3 4 5";
// can split by whitespace to store into an array/lits (I used array for preference) - still string
String[] num_arr = nums.split(" ");
int[] nums_iArr = new int[num_arr.length];
// loop over num_arr, converting element at i to an int and add to int array
for (int i = 0; i < num_arr.length; i++) {
int num_int = Integer.parseInt(num_arr[i])
nums_iArr[i] = num_int
}
That pretty much covers it. If you wanted to output them, to console for instance:
// for each loop to output
for (int i : nums_iArr) {
System.out.println(i);
}
I would like to introduce tokenizer class to split by any delimiter. Input string is scanned only once and we have a list without extra loops.
String value = "1, 2, 3, 4, 5";
List<Long> list=new ArrayList<Long>();
StringTokenizer tokenizer = new StringTokenizer(value, ",");
while(tokenizer.hasMoreElements()) {
String val = tokenizer.nextToken().trim();
if (!val.isEmpty()) list.add( Long.parseLong(val) );
}
split it with space, get an array then convert it to list.
You can split it and afterwards iterate it converting it into number like:
String[] strings = "1 2 3".split("\\ ");
int[] ints = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
ints[i] = Integer.parseInt(strings[i]);
}
System.out.println(Arrays.toString(ints));
You first split your string using regex and then iterate through the array converting every value into desired type.
String[] literalNumbers = [number.split(" ");][1]
int[] numbers = new int[literalNumbers.length];
for(i = 0; i < literalNumbers.length; i++) {
numbers[i] = Integer.valueOf(literalNumbers[i]).intValue();
}
I needed a more general method for retrieving the list of integers from a string so I wrote my own method.
I'm not sure if it's better than all the above because I haven't checked them.
Here it is:
public static List<Integer> getAllIntegerNumbersAfterKeyFromString(
String text, String key) throws Exception {
text = text.substring(text.indexOf(key) + key.length());
List<Integer> listOfIntegers = new ArrayList<Integer>();
String intNumber = "";
char[] characters = text.toCharArray();
boolean foundAtLeastOneInteger = false;
for (char ch : characters) {
if (Character.isDigit(ch)) {
intNumber += ch;
} else {
if (intNumber != "") {
foundAtLeastOneInteger = true;
listOfIntegers.add(Integer.parseInt(intNumber));
intNumber = "";
}
}
}
if (!foundAtLeastOneInteger)
throw new Exception(
"No matching integer was found in the provided string!");
return listOfIntegers;
}
The #key parameter is not compulsory. It can be removed if you delete the first line of the method:
text = text.substring(text.indexOf(key) + key.length());
or you can just feed it with "".

Categories