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.
Related
String Str = new String("(300+23)*(43-21)/(84+7)");
System.out.println("Return Value :" );
String[] a=Str.split(Str);
String a="("
String b="300"
String c="+"
I want to convert this single string to an array giving output as above till the end of the equation using split method any suggestions
The above code doesn't works for it
When you write Str.split(Str); , the parameter of the split function should be the string by which you want to break the bigger string into an array of smaller strings.
For example,
String s = "this is a string";
String [] array = s.split(" ");
The parameter for the split function here is basically just a space, so the split function will break the s string into parts delimited by the " " spring, which will result in array having the following values: {"this", "is", "a", "string"}.
I think this example is conclusive. What you are doing in your code is basically trying to break your string into parts using the string itself, which of course makes no sense.
You won't find an answer to what you want to achieve using just the split function, because there is no good string to act like a token by which to delimit the bigger string.
You could use a simple regular expression to achieve what you want, e.g.
public static void main(final String[] args) {
final String string = "(300+23)*(43-21)/(84+7)";
final String[] arr = string.split("(?<![\\d.])|(?![\\d.])");
for (final String s : arr)
System.out.println(s);
}
Has to be modified a bit if whitespace could be present etc. but works for your example input string.
This may sound a bit strange but I'm trying to only show part of a string that is retrieved. The string that is retrieved contains something only the lines of NAME:myname and I'm trying to only show the "myname" part is there a way to 'disect' a string considering I know what the prefix "NAME:" is all ways going to be?
There are plenty of ways:
Replace "NAME:" by nothing.
String cleaned = myString.replace("NAME:", "");
Split the string (as shown in the other answer).
Cut the string (if it always starts with NAME: which length is 5):
String cleaned = myString.subString(5);
Use a regular expression
Probably 200 other ways.
Yes. Use something like:
String arr[] = myString.Split(":");
String name = arr[1];
arr[] will contain 2 elements (0 and 1).
arr[0] will contain "Name"
and
arr[1] will contain the second part (the name itself)
Another version of the same (1 line only):
String name = myString.Split(":")[1];
Use split method :
String name = tmpStr.split(":")[tmpStr.split(":").length-1] ;
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.
I need to convert String[] to Byte[] in Java. Essentially, I have a space delimited string returned from my database. I have successfully split this String into an array of string elements, and now I need to convert each element into a byte, and produce a byte[] at the end.
So far, the code below is what I have been able to put together but I need some help making this work please, as the getBytes() function returns a byte[] instead of a single byte. I only need a single byte for the string (example string is 0xd1 )
byte[] localbyte = null;
if(nbytes != null)
{
String[] arr = (nbytes.split(" "));
localbyte = new byte[arr.length];
for (int i=0; i<localbyte.length; i++) {
localbyte[i] = arr[i].getBytes();
}
}
I assume you'd like to split strings like this:
"Hello world!"
Into "Hello", "world!" instead of "Hello", " ", "world!"
If that's the case, you can simply tweak on the split regex, using this instead:
String[] arr = (nbytes.split(" +"));
You should be familiar with regular expression. Instead of removing empty string after splitting, you can split the string with one or more white space:
To split a string by space or tab, you can use:
String[] arr = (nbytes.split("\\p{Blank}+"));
E.g.
"Hello \tworld!"
results in
"Hello","world!"
To split a string by any whitespace, you can use:
String[] arr = (nbytes.split("\\p{Space}+"));
E.g
"Hello \tworld!\nRegular expression"
results in
"Hello","world!","Regular","expression"
What about Byte(String string) (Java documentation).
Also you might want to look up Byte.parseByte(string) (doc)
byte[] localbyte = null;
if(nbytes != null)
{
String[] arr = (nbytes.split(" "));
localbyte = new byte[arr.length];
for (int i=0; i<localbyte.length; i++) {
localbyte[i] = new Byte(arr[i]);
}
}
Notice:
The characters in the string must all be decimal digits, except that
the first character may be an ASCII minus sign '-' ('\u002D') to
indicate a negative value.
So you might want to catch the NumberFormatException.
If this is not what your looking for maybe you can provide additional information about nbytes ?
Also Michael's answer could turn out helpful: https://stackoverflow.com/a/2758746/1063730
My android application takes sms messages from a BroadcastReceiver and copies the message into a new sms. Then forwards it. Due to technical reasons I must to split the sms and copy only the portions after split[2]:
public string splitAndReturnRest(String inputStr)
{
String[] split = inputStr.split("\\s"); // split where spaces
// now ignore split[0], split[1], split [2], copy rest of the split parts into
String restOfTheSplits=//copy rest of the splits except split[0], split[1], split[2]
return restOfTheSplits;
}
The problem is I can't just hard code it. I do not know how many parts the message contains. So the number of elements after split[2] is unknown to me and may change every time. Perhaps I need some kind of for loop, or a different split criteria?
After split[2], use the following....
String restOfTheSplits = null;
for (int i=3 ; i<split.length; i++)
{
restOfTheSplits = restOfTheSplits + split[i];
}
return restOfTheSplits
Its even better if you use StringBuilder to get the restOfTheSplits and then convert it to String and return it....