I am trying to print my string in the following format. ua, login, login ---> ua, navigation, fault Average = 500 milliseconds. I am storing the 2 strings into one string called keyString and putting it into the hashmap seperated by "|". I am then splitting that when I am iterating over the keyset to get it in the format I originally stated but it is showing up like this ---> ua, ctiq, export|ua, ctiq export, transfer Average = 600 milliseconds. Any ideas?
public static void ProcessLines(Map<String, NumberHolder> uaCount,String firstLine, String secondLine) throws ParseException
{
String [] arr1 = firstLine.split("-- ", 2);
String [] arr2 = secondLine.split("-- ", 2);
String str1 = arr1[1];
String str2 = arr2[1];
......
String keyString = str1 + "|" + str2;
NumberHolder hashValue = uaCount.get(keyString);
if(hashValue == null)
{
hashValue = new NumberHolder();
uaCount.put(keyString, hashValue);
}
hashValue.sumtime_in_milliseconds += diffMilliSeconds;
hashValue.occurences++;
public static class NumberHolder
{
public int occurences;
public int sumtime_in_milliseconds;
}
and heres the printing part
for(String str : uaCount.keySet())
{
String [] arr = str.split("|",2);
long average = uaCount.get(str).sumtime_in_milliseconds / uaCount.get(str).occurences;
//System.out.println(str);
System.out.println(arr[0] + " ---> " + arr[1] + " Average = " + average + " milliseconds");
}
split uses regular expression to match place to split, and in "RegEx" | means OR. To use | as literal you need to escape it with \ which in String is written as "\\". Alternatively you can use [|]. Try
str.split("\\|",2);
Related
This post is an update to this one : get specific character in a string with regex and remove unused zero
In the first place, i wanted to remove with an regular expression the unused zero in the last match.
I found that the regular expression is a bit overkill for what i need.
Here is what i would like now,
I would like to use split() method
to get from this :
String myString = "2020-LI50532-3329-00100"
this :
String data1 = "2020"
String data2 = "LI50532"
String data3 = "3329"
String data4 = "00100"
So then i can remove from the LAST data the unused Zero
to convert "00100" in "100"
And then concatenate all the data to get this
"2020-LI50532-3329-100"
Im not familiar with the split method, if anyone can enlight me about this ^^
You can use substring method to get rid of the leading zeros...
String myString = "2020-LI50532-3329-00100";
String[] data = myString.split("-");
data[3] = data[3].substring(2);
StringBuilder sb = new StringBuilder();
sb.append(data[0] + "-" + data[1] + "-" + data[2] + "-" + data[3]);
String result = sb.toString();
System.out.println(result);
Assuming that we want to remove the leading zeroes of ONLY the last block, maybe we can:
Extract the last block
Convert it to Integer and back to String to remove leading zeroes
Replace the last block with the String obtained in above step
Something like this:
public String removeLeadingZeroesFromLastBlock(String text) {
int indexOfLastDelimiter = text.lastIndexOf('-');
if (indexOfLastDelimiter >= 0) {
String lastBlock = text.substring(indexOfLastDelimiter + 1);
String lastBlockWithoutLeadingZeroes = String.valueOf(Integer.valueOf(lastBlock)); // will throw exception if last block is not an int
return text.substring(0, indexOfLastDelimiter + 1).concat(lastBlockWithoutLeadingZeroes);
}
return text;
}
Solution using regex:
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parse("2020-LI50532-3329-00100"));
System.out.println(parse("2020-LI50532-3329-00001"));
System.out.println(parse("2020-LI50532-03329-00100"));
System.out.println(parse("2020-LI50532-03329-00001"));
}
static String parse(String str) {
return str.replaceAll("0+(?=[1-9]\\d*$)", "");
}
}
Output:
2020-LI50532-3329-100
2020-LI50532-3329-1
2020-LI50532-03329-100
2020-LI50532-03329-1
Explanation of the regex:
One or more zeros followed by a non-zero digit which can be optionally followed by any digit(s) until the end of the string (specified by $).
Solution without using regex:
You can do it also by using Integer.parseInt which can parse a string like 00100 into 100.
public class Main {
public static void main(String[] args) {
// Test
System.out.println(parse("2020-LI50532-3329-00100"));
System.out.println(parse("2020-LI50532-3329-00001"));
System.out.println(parse("2020-LI50532-03329-00100"));
System.out.println(parse("2020-LI50532-03329-00001"));
}
static String parse(String str) {
String[] parts = str.split("-");
try {
parts[parts.length - 1] = String.valueOf(Integer.parseInt(parts[parts.length - 1]));
} catch (NumberFormatException e) {
// Do nothing
}
return String.join("-", parts);
}
}
Output:
2020-LI50532-3329-100
2020-LI50532-3329-1
2020-LI50532-03329-100
2020-LI50532-03329-1
you can convert the last string portion to integer type like below for removing unused zeros:
String myString = "2020-LI50532-3329-00100";
String[] data = myString.split("-");
data[3] = data[3].substring(2);
StringBuilder sb = new StringBuilder();
sb.append(data[0] + "-" + data[1] + "-" + data[2] + "-" + Integer.parseInt(data[3]));
String result = sb.toString();
System.out.println(result);
You should avoid String manipulation where possible and rely on existing types in the Java language. One such type is the Integer. It looks like your code consists of 4 parts - Year (Integer) - String - Integer - Integer.
So to properly validate it I would use the following code:
Scanner scan = new Scanner("2020-LI50532-3329-00100");
scan.useDelimiter("-");
Integer firstPart = scan.nextInt();
String secondPart = scan.next();
Integer thirdPart = scan.nextInt();
Integer fourthPart = scan.nextInt();
Or alternatively something like:
String str = "00100";
int num = Integer.parseInt(str);
System.out.println(num);
If you want to reconstruct your original value, you should probably use a NumberFormat to add the missing 0s.
The main points are:
Always try to reuse existing code and tools available in your language
Always try to use available types (LocalDate, Integer, Long)
Create your own types (classes) and use the expressiveness of the Object Oriented language
public class Test {
public static void main(String[] args) {
System.out.println(trimLeadingZeroesFromLastPart("2020-LI50532-03329-00100"));
}
private static String trimLeadingZeroesFromLastPart(String input) {
String delem = "-";
String result = "";
if (input != null && !input.isEmpty()) {
String[] data = input.split(delem);
StringBuilder tempStrBldr = new StringBuilder();
for (int idx = 0; idx < data.length; idx++) {
if (idx == data.length - 1) {
tempStrBldr.append(trimLeadingZeroes(data[idx]));
} else {
tempStrBldr.append(data[idx]);
}
tempStrBldr.append(delem);
}
result = tempStrBldr.substring(0, tempStrBldr.length() - 1);
}
return result;
}
private static String trimLeadingZeroes(String input) {
int idx;
for (idx = 0; idx < input.length() - 1; idx++) {
if (input.charAt(idx) != '0') {
break;
}
}
return input.substring(idx);
}
}
Output:
2020-LI50532-3329-100
I have 3 String like this:
["state","in",["assigned", "partially_available"]]
["state","in",["confirmed", "waiting"]]
["state","in",["confirmed", "waiting", "assigned"]]
Now I want to convert each string to 2 arrays with first 2 elements is a array and others elements is a array(Ex: ["state", "in"] ["asigned", "partially_available"]). Any way to do that? Thank you very much!
String s = "[state,in,[assigned, partially_available]]";
s = s.substring(1,s.length()-1); // removes first and last square bracket
String[] sArr = s.split(",(?! )"); // split only the comma which is not followed by a space character
String[] newArr1 = {sArr[0],sArr[1]}; // first array containing ["state","in"]
String temp = sArr[2].substring(1,sArr[2].length()-1); // remove the square brackets from the inner array
String[] newArr2 = {temp.split(",")[0],temp.split(",")[1]}; // second array containing ["asigned", "partially_available"]
Try this.
public class TestArray{
public static void main(String[] args) {
String string = "[state,in,[assigned, partially_available]]";
String[] tempstr = string.split("\\["); //remove "["
String arrayFirstElement = tempstr[1].substring(0,tempstr[1].length()-1);
String arraySecondElement = tempstr[2].substring(0, tempstr[2].length()-2);
System.out.println("arrayFirstElement : " + arrayFirstElement);
System.out.println("arraySecondElement : " + arraySecondElement);
String[] strArray = new String[2];
strArray[0] = arrayFirstElement;
strArray[1] = arraySecondElement;
System.out.println("strArray[0] : " + strArray[0] + " AND strArray[1] : " + strArray[1]);
}
}
In a Java code, I have 11 different strings, some of them (at most 9) can be null. Strings are a part of an object. If none of them is null, I make a string like this :
string1 + "," + string2 + "," + string3 + "," + string4 + "," + string5 + "," + string6 + "(" + string7 + ")" + string8 + string9 + "+" + string10 + string11
If none of them is null, it's okey. But some of them can be null. If I check if each of them is null, code gets really slow and long. How can I generate such a string in an efficient and fast way? Thanks.
public static void main(String[] args) {
String string1 = "test1";
String string2 = "test2";
String string3 = "test3";
String string4 = null;
String string5 = "test5";
StringBuilder stringBuilder = new StringBuilder();
List<String> valueList = new ArrayList<>();
valueList.add(string1);
valueList.add(string2);
valueList.add(string3);
valueList.add(string4);
valueList.add(string5);
// etc.
for (String value : valueList) {
if (value != null) {
stringBuilder.append(value);
}
else {
value = ",";
stringBuilder.append(value);
}
}
System.out.println(stringBuilder);
}
Output :
test1test2test3,test5
With Java 8 you could use this for the first part with comma-delimited strings:
String part1 = Stream.of(string1, string2, string3, string4, string5, string6)
.filter(Objects.notNull())
.collect(joining(",");
From then on you have an irregular structure so you'll need custom logic to handle it. The helper function
static String emptyForNull(String s) {
return s == null ? "" : s;
}
can get you part of the way.
In Java 8, you can stream and join with Collectors, and filter with Objects classes
List<String> strings = Arrays.asList("first", "second", null, "third", null, null, "fourth");
String res = strings.stream().filter(Objects::nonNull).collect(Collectors.joining(","));
System.out.println(res);
results in output
first,second,third,fourth
If you simply want your code to be as short as possible, use String.format and get rid of the "null" in the string.
String result = String.format("%s,%s,%s,%s,%s,%s(%s)%s,%s,%s,%s",
string1, string2, string3, string4, string5,
string6, string7, string8, string9, string10,
string11);
System.out.println(result.replace("null", ""));
If 6th index of your string is always surrounded by ( and ) then you can use following code.
List<String> vals = new ArrayList<>();
vals.add(string1);
vals.add(string2);
vals.add(string3);
vals.add(string4);
vals.add(string5);
vals.add(string6);
vals.add(string7);
vals.add(string8);
vals.add(string9);
vals.add(string10);
vals.add(string11);
for (int i =0 ; i < vals.size(); i++) {
// check null values
if (vals.get(i) != null) {
// as your requirement surround 7th value with ( and )
if(vals.indexOf(vals.get(i)) == 6) {
values += "\b(" + vals.get(i)+")";
} else {
values += vals.get(i)+",";
}
}
}
System.out.println(values+"\b");
Output
if 4th and 9th strings are null then,
test1,test2,test3,test5,test6(test7)test8,test10,test11
I am trying to get an element from my string wich I have attained thtough a getSelectedValue().toString from a JList.
It returns [1] testString
What I am trying to do it only get the 1 from the string. Is there a way to only get that element from the string or remove all else from the string?
I have tried:
String longstring = Customer_list.getSelectedValue().toString();
int index = shortstring.indexOf(']');
String firstPart = myStr.substring(0, index);
You have many ways to do it, for example
Regex
String#replaceAll
String#substring
See below code to use all methods.
import java.util.*;
import java.lang.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Test {
public static void main(String args[]) {
String[] data = { "[1] test", " [2] [3] text ", " just some text " };
for (String s : data) {
String r0 = null;
Matcher matcher = Pattern.compile("\\[(.*?)\\]").matcher(s);
if (matcher.find()) {
r0 = matcher.group(1);
}
System.out.print(r0 + " ");
}
System.out.println();
for (String s : data) {
String r1 = null;
r1 = s.replaceAll(".*\\[|\\].*", "");
System.out.print(r1 + " ");
}
System.out.println();
for (String s : data) {
String r2 = null;
int i = s.indexOf("[");
int j = s.indexOf("]");
if (i != -1 && j != -1) {
r2 = s.substring(i + 1, j);
}
System.out.print(r2 + " ");
}
System.out.println();
}
}
However results may vary, for example String#replaceAll will give you wrong results when input is not what you expecting.
1 2 null
1 3 just some text
1 2 null
What worked best for me is the String#replace(charSequence, charSequence) combined with String#substring(int,int)
I have done as followed:
String longstring = Customer_list.getSelectedValue().toString();
String shortstring = longstring.substring(0, longstring.indexOf("]") + 1);
String shota = shortstring.replace("[", "");
String shortb = shota.replace("]", "");
My string has been shortened, and the [ and ] have been removed thereafter in 2 steps.
Running this method gives a string of total post output
String numberOfPost = test.runNewAdvancedSearch(query, waitTime, startDate, endDate, selectedBrowser, data1, "");
int numberOfPostsInt = Integer.parseInt(numberOfPosts.replace(",", ""));
this parseInt does not work
How do I parse this out below?
"Total Posts: 5,203"
Try this fully functional example:
public class Temp {
public static void main(String[] args) {
String s = "Total Posts: 5,203";
s = s.replaceAll("[^0-9]+", "");
System.out.println(s);
}
}
Meaning of the regex pattern [^0-9]+ - Remove all characters which occurs one or more times + which does NOT ^ belong to the list [ ] of characters 0 to 9.
if comma is decimal separator:
double d = Double.parseDouble(s.substring(s.lastIndexOf(' ') + 1).replace(",", "."));
if comma is grouping separator:
long d = Long.parseLong(s.substring(s.lastIndexOf(' ') + 1).replace(",", ""));
Try This:
String numberOfPost = test.runNewAdvancedSearch(query, waitTime, startDate, endDate, selectedBrowser, data1, ""); // get the parse string "Total Posts: 5,203
int index = numberOfPost.lastIndexOf(":");
String number = numberOfPost.substring(index + 1);
int numOfPost = Integer.parseInt(number.replace(",", "").trim());
System.out.println(numOfPost); // 5203enter code here