Splitting a String built from a char array - java

I'm trying to split a specific String of the format
0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;
in order to extract and save value01 and value02. How can I do this?
Here is what i tried so far:
//buffer contains a String like: "0001,0004,dd/mm/yy hh:mm:ss,01,18,750"
String string = new String(buffer,0,len);
String[] parts = string.split(",");
String temp = parts[5];
String lum = parts[6];
System.out.print(temp);
System.out.print(lum);
With this code I get ArrayIndexOutofBounds when running the program in Netbeans.
Image of error description
Also tried this method:
//buffer contains a String like: "0001,0004,dd/mm/yy hh:mm:ss,01,18,750"
String s= new String(buffer,0,len);
String aux = s + ",";
String[] dados = aux.split(",");
float valor1 = Float.parseFloat(dados[5]);
float valor2 = Float.parseFloat(dados[6]);
System.out.print(aux);

This:
String temp = parts[5];
String lum = parts[6];
Should be this:
String temp = parts[4];
String lum = parts[5];
Remember that arrays in Java are zero-based. So if you do this:
String[] parts = "0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02".split(",");
Then "0001" would be in parts[0], "0004" in parts[1], "value01" in parts[4] etc.

Achieving what you're trying to do is acutally pretty easy.
Assuming that your string really always looks like:
0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;
Just cut off the start of the string which you don't need and extract the values afterwards:
// This can be done in hundreds of ways, for the sake of simplicity i'll use substring
String s ="0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;";
String cutOff = s.substring(31, s.length()-1);
String[] results = cutOff.split(",");

please find below code. It has just a bit modification in Andrew's code. Since we are storing the string after splitting into a String array and it's obvious that array index starts with 0. That's why in order to get value01 and value02, we should use index 4 and 5.
public class JavaApplication1
{
public static void main(String[] args)
{
String str="0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02";
String [] strArr=str.split(",");
String temp=strArr[4];
String lum=strArr[5];
System.out.println(temp);
System.out.println(lum);
}
}

Related

How can get string which seprated by delimeted symbol ( | ) in text file using java?

I having test file in my java project directory which having below content:
HEADER|INPUT|2017|test|1
|Id|Name|
From where I want to update " Id " value from another string "xyz"
"ID" is not static everytime this value gets changed
How can I get particular string using java?
You can use the split function. This will return your string split into the parts, seperated by |.
var result = "HEADER|INPUT|2017|test|1 |Id|Name|".split("\\|");
// Access an array
// result[0] will be 'Header'
Source
You can use String.split() function:
String string = "HEADER|INPUT|2017|test|1 |Id|Name|";
String[] parts = string.split("\\|");
String part1 = parts[0]; // HEADER
String part2 = parts[1]; // INPUT
String part3=parts[2]; //2017
and so on.
You can make use of split() method here to divide your string as per your requirement.
String input= "HEADER|INPUT|2017|test|1 |Id|Name|";
String[] contents = input.split("\\|");
String name = input[6];
String id = input[5];
String number = input[4];
String test = input[3];
String year = input[2];
String input = input[1];
String header = input[0];
For more on String.split()

Java - Cut a string programmatically

I have a string (URL) like this:
"https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp"
I need to extract the last part only i.e. 02_Cuppy_lol.webp.
How can I do that?
Thanks!
You can use substring() and lastIndexOf() here:
String value = completeString.substring(completeString.lastIndexOf("/") + 1);
You can split this text/url and get last part, for example:
String url = "https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] splittedUrl = url.split("/");
String lastPart = splittedUrl[splittedUrl.length()-1)];
you can use the method split().follow this example
public class Demo {
public static void main(String args[]){
String str ="https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] temp=str.split("/");
int lastIndex =temp.length-1;
String lastPart = temp[lastIndex];
System.out.println(lastPart);
}
}
Output-:
02_Cuppy_lol.webp

Any shortest method to get RHS values in the string with comma separated

This is my String
String str = "fus=""192.10.136.111"""," ful=""333333"""," fui=""7b7b7b40000000010000012e55192ab8""", fuc=1, fuq=3, fut=2015-03-30 16:21:36, fud=1, fss=3, fst=2," fsi=""302""", fso=0, fsa=0, fsr=2, cuc=1".
I need only the RHS values without double quotes with comma seperated. For example
192.10.136.111,333333,7b7b7b40000000010000012e55192ab8,1,3,2015-03-30 16:21:36,1,3,2,302,0,0,2,1
The logic should be generic
If you have a string like below (which is basically a CSV of key-value pair)
String str = "fus=\"192.168.1.1\",fus1=\"333333\"";
You can use below code
List<String> values = new ArrayList<>();
String [] keyValuePairs = str.split(",");
for(String keyValuePair : keyValuePairs) {
String [] keyValue = keyValuePair.split("=");
values.add(keyValue[1]);
}
Seeing that this is only your second question, you need to get into a habit of providing MCVE. You posted your problem, but you didn't post an attempt or even an explanation of an attempt.
Having said that, after escaping all of the quotations in your string, you could try simple string manipulations.
public static void main(String[] args) throws Exception {
String str = "fus=\"\"192.10.136.111\"\"\",\" ful=\"\"333333\"\"\",\" fui=\"\"7b7b7b40000000010000012e55192ab8\"\"\", fuc=1, fuq=3, fut=2015-03-30 16:21:36, fud=1, fss=3, fst=2,\" fsi=\"\"302\"\"\", fso=0, fsa=0, fsr=2, cuc=1";
String[] pieces = str.split(",");
for (int i = 0; i < pieces.length; i++) {
pieces[i] = pieces[i].substring(pieces[i].indexOf("=") + 1).replaceAll("\"", "");
}
System.out.println(String.join(",", pieces));
}
Results:

Java get the same String after split

In Java if you want to split a String by a char or a String you can do that by the split method as follow:
String[] stringWords = myString.split(" ");
But let's say i want now to create a new String using the strings in stringWords using the char * between them. Is there any solutions to do it without for/while instructions?
Here is a clear example:
String myString = "This is how the string should be";
String iWant = "This*is*how*the*string*should*be";
Somebody asks me to be more clear why i don't want just to use replace() function. I don't want to use it simply because the content of the array of strings (array stringWords in my example) changes it's content.
Here is an example:
String myString = "This is a string i wrote"
String[] stringWords = myString.split(" ");
myAlgorithmFucntion(stringWords);
Here is an example of how tha final string changes:
String iWant = "This*is*something*i*wrote*and*i*don't*want*to*do*it*anymore";
If you don't want to use replace or similar, you can use the Apache Commons StringUtils:
String iWant = StringUtils.join(stringWords, "*");
Or if you don't want to use Apache Commons, then as per comment by Rory Hunter you can implement your own as shown here.
yes there is solution to, split String with special characters like '*','.' etc. you have to use special backshlas.
String myString = "This is how the string should be";
iWant = myString.replaceAll(" ","*"); //or iWant = StringUtils.join(Collections.asList(myString.split(" ")),"*");
iWant = "This*is*how*the*string*should*be";
String [] tab = iWant.split("\\*");
Try something like this as you don't want to use replace() function
char[] ans=myString.toCharArray();
for(int i =0; i < ans.length; i++)
{
if(ans[i]==' ')ans[i]='*';
}
String answer=new String(ans);
Try looping the String array:
String[] stringWords = myString.split(" ");
String myString = "";
for (String s : stringWords){
myString = myString + "s" + "*";
}
Just add the logic to deleting the last * of the String.
Using StringBuilder option:
String[] stringWords = myString.split(" ");
StringBuilder myStringBuilder = new StringBuilder("");
for (String s : stringWords){
myStringBuilder.append(s).append("*");
}

Splitting a period-delimited string into multiple strings

I have a string
String x = "Hello.August 27th.Links.page 1";
I am wondering if I can split this string into 4 other strings based on where the period is. For example, the four other strings would be,
String a = "Hello";
String b = "August 27th";
String c = "Links";
String d = "page 1";
As you can see I basically want to extract certain parts of the string out into a new string, the place where it is extracted is based on where the period is which ends the first string and then shows where the 2nd and, etc. strings end.
Thanks in advance!
In android btw
Use String#split (note that it receives a regex as a parameter)
String x = "Hello.August 27th.Links.page 1";
String[] splitted = x.split("\\.");
Yes of course just use:
String[] stringParts = myString.split("\\.")
String x = "Hello.August 27th.Links.page 1"
String []ar=x.split("[.]");
Perhaps you can use StringTokenizer for this requirement. Here is the simple approach:
String x = "Hello.August 27th.Links.page 1";
if (x.contains(".")) {
StringTokenizer stringTokenizer = new StringTokenizer(x, ".");
String[] arrayOfString = new String[stringTokenizer.countTokens()];
int i = 0;
while (stringTokenizer.hasMoreTokens()) {
arrayOfString[i] = stringTokenizer.nextToken();
i++;
}
System.out.println(arrayOfString[0]);
System.out.println(arrayOfString[1]);
System.out.println(arrayOfString[2]);
System.out.println(arrayOfString[3]);
}
You are done. :)

Categories

Resources