How can i split String in java with custom pattern - java

I am trying to get the location data from this string using String.split("[,\\:]");
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
String[] str = location.split("[,\\:]");
How can i get the data like this.
str[0] = 27.980194
str[1] = 46.090199
str[2] = 0.48
str[3] = 1
str[4] = 6
Thank you for any help!

If you just want to keep the numbers (including dot separator), you can use:
String[] str = location.split("[^\\d\\.]+");
You will need to ignore the first element in the array which is an empty string.
That will only work if the data names don't contain numbers or dots.

String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
Matcher m = Pattern.compile( "\\d+\\.*\\d*" ).matcher(location);
List<String> allMatches = new ArrayList<>();
while (m.find( )) {
allMatches.add(m.group());
}
System.out.println(allMatches);

Quick and Dirty:
String location = "$,lat:27.980194,lng:46.090199,speed:0.48,fix:1,sats:6,";
List<String> strList = (List) Arrays.asList( location.split("[,\\:]"));
String[] str = new String[5];
int count=0;
for(String s : strList){
try {
Double d =Double.parseDouble(s);
str[count] = d.toString();
System.out.println("In String Array:"+str[count]);
count++;
} catch (NumberFormatException e) {
System.out.println("s:"+s);
}
}

Related

How to take input in expected form in java?

I want to take a string input in
%d+%d
format in java.How do i do it?
I know that I can do this with string.split() method. But I feel that it is going to be way more complex if I had to deal with more strings in input. Like
%d+%d-%d
I am looking for solutions that are close to a scanf solution for c.
I tried this for %d+%d
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
String first,second;
String[] arr = str.split("\\+");
first = arr[0];
second = arr[1];
scanner.close();
And this for %d+%d-%d+%d..........=%d-%d+%d.....+%d...
private final String[] splitLoL(String txt) {
LinkedList<String> strList1 = new LinkedList<String>();
LinkedList<String> strList2 = new LinkedList<String>();
LinkedList<String> strList3 = new LinkedList<String>();;
strList1.addAll(Arrays.asList(txt.split("\\+")));
for(String str : strList1) {
String[] proxy = str.split("-");
strList2.addAll(Arrays.asList(proxy));
}
for(String str : strList2) {
String[] proxy = str.split("=");
strList3.addAll(Arrays.asList(proxy));
}
String[] strArr = new String[strList3.size()];
for(int i = 0; i < strArr.length; i++) {
strArr[i] = new String(strList3.get(i));
}
return strArr;
}
Try this:
String str = scanner.nextLine();
List<String> str2 = new ArrayList();
Matcher m = Pattern.compile("\\d+").matcher(str);
while(m.find()) {
str2.add(m.group());
}
Or you can do the following using JDK 9+:
import java.util.Scanner;
public class ScannerTrial {
public static void main(String[] args) {
Scanner scanner = new Scanner(" 4 z zz ggg 22 e");
scanner.findAll("\\d+").forEach((e) -> System.out.println(e.group()));
}
}
This would print
4 22

Java .split() out of bounds

I have a problem with my code.
I'm trying to extract the name of the channels from a .txt file.
I can't understand why the method line.split() give me back an array with 0 length:
Someone can help me?
This is the file .txt:
------------[channels.txt]---------------------
...
#CH id="" tvg-name="Example1" tvg-logo="http...
#CH id="" tvg-name="Example2" tvg-logo="http...
#CH id="" tvg-name="Example3" tvg-logo="http...
#CH id="" tvg-name="Example4" tvg-logo="http...
...
This is my code:
try {
FileInputStream VOD = new FileInputStream("channels.txt");
BufferedReader buffer_r = new BufferedReader(new InputStreamReader(VOD));
String line;
ArrayList<String> name_channels = new ArrayList<String>();
while ((line = buffer_r.readLine()) != null ) {
if (line.startsWith("#")) {
String[] first_scan = line.split(" tvg-name=\" ", 2);
String first = first_scan[1]; // <--- out of bounds
String[] second_scan = first.split(" \"tvg-logo= ", 2);
String second = second_scan[0];
name_channels.add(second);
} else {
//...
}
}
for (int i = 0; i < name_channels.size(); i++) {
System.out.println("Channel: " + name_channels.get(i));
}
} catch(Exception e) {
System.out.println(e);
}
So you have examples like this
#CH id="" tvg-name="Example1" tvg-logo="http...
And are trying to split on these strings
" tvg-name=\" "
" \"tvg-logo= "
Neither of those strings are in the example. There's a spurious space appended, and the space at the start of the second is in the wrong place.
Fix the strings and here's a concise but complete program to demonstrate
interface Split {
static void main(String[] args) {
String line = "#CH id=\"\" tvg-name=\"Example1\" tvg-logo=\"http...";
String[] first_scan = line.split(" tvg-name=\"", 2);
String first = first_scan[1]; // <--- out of bounds
String[] second_scan = first.split("\" tvg-logo=", 2);
String second = second_scan[0];
System.err.println(second);
}
}
Of course, if you have any lines that start with '#' but don't match, you'll have a similar problem.
This sort of thing is probably done better with regexs and capturing groups.
There is a whitespace after the last double quote in tvg-name=\" which does not match the data in your example.
When you use split with line.split(" tvg-name=\"", 2) then the first item in the returned array will be #CH id="" and the second part will be Example1" tvg-logo="http..."
If you want to get the value of tvg-name= you might use a regex with a capturing group where you would capture not a double quote using a negated character class [^"]+
tvg-name="([^"]+)"
try {
FileInputStream VOD = new FileInputStream("channels.txt");
BufferedReader buffer_r = new BufferedReader(new InputStreamReader(VOD));
String line;
ArrayList<String> name_channels = new ArrayList<String>();
while((line = buffer_r.readLine()) != null ){
if(line.startsWith("#")){
String regex = "tvg-name=\"([^\"]+)\"";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
while (matcher.find()) {
name_channels.add(matcher.group(1));
}
} else {
// ...
}
}
for(int i = 0; i < name_channels.size(); i++){
System.out.println("Channel: " + name_channels.get(i));
}
}catch(Exception e){
System.out.println(e);
}

How to convert a string contains array format to java array or list?

I have a string like this:
String res = '["A","B","0","1"]';
How to convert it to an array or list in Java to become like this:
String[] r = {"A","B","0","1"};
Since your string is a correct Json string, you may use the gson library:
String s = "[\"A\",\"B\",\"0\",\"1\"]";
Gson gson = new GsonBuilder().create();
String[] arr = gson.fromJson(s, String[].class);
// {"A","B","0","1"}
Without using Gson, You can get the desired result by following below approach -
String inputStr = "[\"A\",\"B\",\"0\",\"1\"]";
String[] strArray = inputStr.split("[^\\w\\d]");
List<String> list = new ArrayList<>();
for (String str : strArray) {
if (str != null && !str.isEmpty()) {
list.add(str);
}
}
System.out.println(list);
Output will be: [A, B, 0, 1]
String res = "[A,B,0,1]";
res = res.replace("[", "");
res = res.replace("]", "");
res = res.replaceAll(",", "");
String [] arrayOutput = new String [res.length()];
char [] ar = res.toCharArray();
for(int i = 0; i< ar.length; i++)
{
char buffer = ar[i];
arrayOutput[i] = String.valueOf(buffer);
}

Parse hashtags between symbols

I need to parse hashtags from String (test comment #georgios#gsabanti sefse #afa).
String text = "test comment #georgios#gsabanti sefse #afa";
String[] words = text.split(" ");
List<String> tags = new ArrayList<String>();
for ( final String word : words) {
if (word.substring(0, 1).equals("#")) {
tags.add(word);
}
}
In the end i need an Array with "#georgios" , "#gsabanti" , "#afa" elements.
But now #georgios#gsabanti showing like one hashtag.
How to fix it?
+1 for the Regular Expressions:
Matcher matcher = Pattern.compile("(#[^#\\s]*)")
.matcher("test comment #georgios#gsabanti sefse #afa");
List<String> tags = new ArrayList<>();
while (matcher.find()) {
tags.add(matcher.group());
}
System.out.println(tags);
Here is a simple way of doing that
String text = "test comment #georgios#gsabanti sefse #afa";
String patternst = "#[a-zA-Z0-9]*";
Pattern pattern = Pattern.compile(patternst);
Matcher matcher = pattern.matcher(text);
List<String> tags = new ArrayList<String>();
while (matcher.find()) {
tags.add(matcher.group(0));
}
I hope it will work for you :)
Use Arraylist instead of array:
String text = "test comment #georgios#gsabanti sefse #afa";
ArrayList<String> hashTags = new ArrayList()<>;
char[] c = text.toCharArray();
for(int i=0;i<c.length;i++) {
if(c[i]=='#') {
String hash = "";
for(int j=i+1;j<c.length;j++) {
if(c[j]==' ' || c[j]=='#') {
hashTags.add(hash);
hash="";
break;
}
hash+=c[j];
}
}
}
String text = "test comment #georgios#gsabanti sefse #afa";
String[] words = text.split("(?=#)|\\s+")
List<String> tags = new ArrayList<String>();
for ( final String word : words) {
if (!word.isEmpty() && word.startsWith("#")) {
tags.add(word);
}
}
You can split your string at " " or "#" and keep the delimiters and filter those out which start with "#" like below:
public static void main(String[] args){
String text = "test comment #georgios#gsabanti sefse #afa";
String[] tags = Stream.of(text.split("(?=#)|(?= )")).filter(e->e.startsWith("#")).toArray(String[]::new);
System.out.println(Arrays.toString(tags));
}

String reverse using Java'sstringbuilder

I develop using Java to make a little project.
I want String reverse.
If I entered "I am a girl", Printed reversing...
Already I tried to use StringBuilder.
Also I write it using StringBuffer grammar...
But I failed...
It is not printed my wish...
WISH
My with Print -> "I ma a lrig"
"I am a girl" -> "I ma a lrig" REVERSE!!
How can I do?..
Please help me thank you~!!!
public String reverse() {
String[] words = str.split("\\s");
StringTokenizer stringTokenizer = new StringTokenizer(str, " ");
for (String string : words) {
System.out.print(string);
}
String a = Arrays.toString(words);
StringBuilder builder = new StringBuilder(a);
System.out.println(words[0]);
for (String st : words){
System.out.print(st);
}
return "";
}
Java 8 code to do this :
public static void main(String[] args) {
String str = "I am a girl";
StringBuilder sb = new StringBuilder();
// split() returns an array of Strings, for each string, append it to a StringBuilder by adding a space.
Arrays.asList(str.split("\\s+")).stream().forEach(s -> {
sb.append(new StringBuilder(s).reverse() + " ");
});
String reversed = sb.toString().trim(); // remove trailing space
System.out.println(reversed);
}
O/P :
I ma a lrig
if you do not want to go with lambda then you can try this solution too
String str = "I am a girl";
String finalString = "";
String s[] = str.split(" ");
for (String st : s) {
finalString += new StringBuilder(st).reverse().append(" ").toString();
}
System.out.println(finalString.trim());
}

Categories