Characters Being Added To List<String> - java

I have a List called dbData and two StringBuilders called infoSB and historySB. I've debugged my project and the two StringBuilders have all the data they are supposed to have, but for some reason it also adds some random characters to the data. All I've done to add the data is the code below:
dbData.add(infoSB.toString());
dbData.add(historySB.toString());
The characters being added are [ ] and ,
Has anyone ran into this before and know how to keep it from doing this?
UPDATE: Here is how I'm getting the data and assigning it to the StringBuilder.
JSONObject json_data = jArray.getJSONObject(i);
double altitudeData = json_data.getDouble("altitude");
double altitudeInFeet = altitudeData * 3.281;
historySB.append("Altitude: " + df.format(altitudeInFeet) + "ft\n");

Are these characters at the beginning and end of the string, and is the a comma somewhere in the middle? This is what the toStringmethod of List is meant to do.
If you have a list of three elements
"car"
"van"
"bike"
Then the list will create the following string [car, van, bike]. The [] denote the beginning and end of the list, and commas denote the boundary between elements.
If you just want to concatenate strings then either use the + operator or a StringBuilder / StringBuffer.
eg.
String data = infoSB + historySB;

- First Check your data source, does they carry some sort of odd characters you are receiving.
- I hope what those StringBuilder holds are not JSON, i suspected it cause you are getting [] and , in your StringBuilders , so if it does you need to parse them first and then need to retrieve the specific Data you want....
- You can avoid any dangling whitespaces using trim() method
Eg:
dbData.add(infoSB.toString().trim());
dbData.add(historySB.toString().trim());
///////////////////Edited Part///////////////////
DecimalFormat df = new DecimalFormat("##.###");
String altitudeData = json_data.getString("altitude");
double altitudeInFeet = Double.parseDouble(altitudeData) * 3.281;
historySB.append("Altitude: " + df.format(altitudeInFeet) + "ft\n");

Related

How to make unique string out of substrings?

When I concatenate two strings (e.g. "q5q3q2q1" and "q5q4q3q2q1") I get string that have duplicate substrings q5,q3,q2,q1 which appears twice.
The resultant string would be "q5q3q2q1q5q4q3q2q1" and I need to have each substring (q[number]) appear once i.e."q5q4q3q2q1".
Substring doesn't have to start with 'q', but I could set restriction that it doesn't start with number, also it could have multiple numbers like q11.
What could I use to get this string? If solution could be written in Java that would be good, otherwise only algorithm would be useful.
You can split the concatenated string in groups and then use a set, if order of groups doesn't matter, or a dictionary if it is.
a = "q5q3q2q1"
b = "q5q4q3q2q1"
# Concatenate strings
c = a + b
print(c)
# Create the groups
d = ["q" + item for item in c.split("q") if item != ""]
print(d)
# If order does not matter
print("".join(set(d)))
# If order does matter
print("".join({key: 1 for key in d}.keys()))
Another solution, this one is using regular expression. Concatenate the string and find all patterns ([^\d]+\d+) (regex101). Then add found strings to set to remove duplicates and join them:
import re
s1 = "q5q3q2q1"
s2 = "q5q4q3q2q1"
out = "".join(set(re.findall(r"([^\d]+\d+)", s1 + s2)))
print(out)
Prints:
q5q2q1q4q3
Some quick way of doing this via java as you asked in question:
String a = "q1q2q3";
String b = "q1q2q3q4q5q11";
List l1 = Arrays.asList(a.split("q"));
List l2 = Arrays.asList(b.split("q"));
List l3 = new ArrayList<String>();
l3.addAll(l1);
List l4 = new ArrayList<String>();
l4.addAll(l2);
l4.removeAll(l3);
l3.addAll(l4);
System.out.println(String.join("q", l3));
Output:
q1q2q3q4q5q11
This is a variation of #DanConstantinescu's solution in JS:
Start with the concatenated string.
Split string at the beginning of a substring composed of text followed by a number. This is implemented as a regex lookahead, so split returns the string portions as an array.
Build a set from this array. The constructor performs deduplication.
Turn the set into an array again
Concat the elements with the empty string.
While this code is not Java it should be straightforward to port the idea to other (imperative or object-oriented) languages.
let s_concatenated = "q5q3q2q1" + "q5q4q3q2q1" + "q11a13b4q11"
, s_dedup
;
s_dedup =
Array.from(
new Set(s_concatenated
.split(/(?=[^\d]+\d+)/) // Split into an array
) // Build a set, deduplicating
) // Turn the set into an array again
.join('') // Concat the elements with the empty string.
;
console.log(`'${s_concatenated}' -> '${s_dedup}'.`);

Java parsing last part of a string

I have three strings.
0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1
I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:
0:0:1
1:2:0
3:2:1
I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string
lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);
I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.
String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];
What is a way I could do this? Thanks
Try this:
String l = "your-string";
int temp = l.lastIndexOf('-');
String lastPart = l.substring(temp+1);
Since your requirement concentrate around your need of acquiring the sub-string from the end till - appears first time.
So why not first get the index of last - that appeared in string. And after than extract the sub-string from here till end. Good option. :)
String str = "0:0:0-3:0:0-3:2:0-3:2:1";
String reqStr = str.substring(str.lastIndexOf('-')+1);
reqStr contains the required string. You can use loop with this part of code to extract more such strings.

Replace with empty space

I have done this before, but now I encounter a different problem. I want to extract just the digits at the end "Homework 1: 89", which is in a .txt file. As said I usually used ".replaceAll("[\D]", "")"* . But if I do it ths time, the number before the colon (1 in example) stays... I cannot see of any solution.
it Should look like this:
while (dataSc.hasNextLine()) {
String data = dataSc.nextLine();
ArrayData.add(i, data);
if (data.contains("Homework ")) {
idData.add(a, data);
idData.set(a, (idData.get(a).replaceAll("[\\D]", "")));
Output being, A new string with Just "89"...
Thanks for editing your question.
If you are simply trying to get the end whenever there is the word homework and you can count on the consistent format you can do the following:
String[] tokens = data.split(": ");
System.out.println(tokens[1]);
So if your looking in your code you would be wanting to place this in your if statement where you are trying to get only the numbers after the colon from data.
What the code does it breaks your string into multiple components, breaking it whenever it sees ": ".
In your example of "Homework 1: 89" it will break your data into two "tokens":
1:"Homework 1"
2:"89"
So when accessing the tokens array we access variable tokens[1] because the index starts at 0.
Use below code
1) String str="Homework 1: 89";
str = str.replaceAll("\\D+","");
2) String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
System.out.println(numberOnly);

Java - accessing characters in a string in a 2D-array-like manner?

Is there a more or less easy way (without having to implement it all by myself) to access characters in a string using a 2D array-like syntax?
For example:
"This is a string\nconsisting of\nthree lines"
Where you could access (read/write) the 'f' with something like myString[1][12] - second line, 13th row.
You can use the split() function. Assume your String is assigned to variable s, then
String[] temp = s.split("\n");
That returns an array where each array element is a string on its own new line. Then you can do
temp[1].charAt(3);
To access the 3rd letter (zero-based) of the first line (zero-based).
You could do it like this:
String myString = "This is a string\nconsisting of\nthree lines";
String myStringArr[] = myString.split("\n");
char myChar = myStringArr[1].charAt(12);
To modify character at positions in a string you can use StringBuffer
StringBuffer buf = new StringBuffer("hello");
buf.insert(3, 'F');
System.out.println("" + buf.toString());
buf.deleteCharAt(3);
System.out.println("" + buf.toString());
Other than that splitting into a 2D matrix should be self implemented.
Briefly, no. Your only option is to create an object that wraps and interpolates over that string, and then provide a suitable accessor method e.g.
new Paragraph(myString).get(1,12);
Note that you can't use the indexed operator [number] for anything other than arrays.

Convert from String[] to String and again to String[]

In my JADE program, one agent needs to send an ACL message to another agent. For the agent sending the message (agent1) it stores a String[] array of values that it has to send.
However, in order to actually send the ACL message the content must only be a String and nothing else. The method used add content to the message is the following :
msg.setContent(String str)
So the problem is I have a range of values stored in agent1 , which are all in an array. I have to send these values in ONE message so I can't send several messages with each element of the array. In my current "Test" array I only put two elements so this is what I'm doing so far:
msg.setContent(theArray[0] + theArray[1]);
Now when the receiving agent (agent2) opens this message and gets the content it's obviously just a concatenation of the two elements of the array I sent from agent1.
How do I get agent2 to split this one String back into an array of String[] ? I have looked at the method
split(String regex)
for the String value of the message content. So I'm thinking since each element of the array in Agent1 starts with a Capital letter, then maybe I could enter a regular expression to split String as soon as a capital letter is encountered.
However I'm not sure how to do this, or if it's even a good idea. Please provide any suggestions.
Relevant API doc:
http://jade.cselt.it/doc/api/jade/lang/acl/ACLMessage.html#setContent(java.lang.String)
You can use java.util.Arrays class to convert an array into a string
Like :
String [] myArray = new String[3];
array[0] = "Abc";
array[1] = "Def";
array[2] = "Xyz";
String s =java.util.Arrays.toString(myArray);
So now s will have a string [Abc, Def, Xyz]
Now for converting back from string to string array,
all you have to do is remove those [ and ] first(get the substring) and then split the string.
String myString = s.substring(1, s.length()-1);
String arrayFromString[] = myString.split(", ");
Refer this link java.util.Arrays javadoc
Note: This will not work if your strings contain , (comma and a single space) as mentioned by #jlordo
You can use JSON as an interchange format in order to send pretty much anything as String over the wire.
Here is an example using org.json.
Collection c = Arrays.asList(str);
org.json.JSonArray arr = new org.json.JSonArray(c);
msg.sendContents(arr.toString());
On the other side:
String s = getContents();
org.json.JSonArray arr = new org.json.JSonArray(s);
String[] strs = new String[arr.length()];
for (int i = 0; i < arr.length(); i++) {
strs[i] = arr.getString(i);
}
The solution in Abu's answer will work just fine IF your strings will never ever contain ", ".
If they do, you need to chose something else as the separator (a newline \n for instance). If you cannot be sure about any character never ever appearing in the text, then I guess it cannot be done.

Categories

Resources