Only showing part of string - java

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] ;

Related

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.

Deleting content of every string after first empty space

How can I delete everything after first empty space in a string which user selects? I was reading this how to remove some words from a string in java. Can this help me in my case?
You can use replaceAll with a regex \s.* which match every thing after space:
String str = "Hello java word!";
str = str.replaceAll("\\s.*", "");
output
Hello
regex demo
Like #Coffeehouse Coder mention in comment, This solution will replace every thing if the input start with space, so if you want to avoid this case, you can trim your input using string.trim() so it can remove the spaces in start and in end.
Assuming that there is no space in the beginning of the string.
Follow these steps-
Split the string at space. It will create an array.
Get the first element of that array.
Hope this helps.
str = "Example string"
String[] _arr = str.split("\\s");
String word = _arr[0];
You need to consider multiple white spaces and space in the beginning before considering the above code.
I am not native to JAVA Programming but have an idea that it has split function for string.
And the reference you cited in the question is bit complex, while you can achieve the desired thing very easily.
P.S. In future if you make a mind to get two words or three, splitting method is better (assuming you have already dealt with multiple white-spaces) else substring is better.
A simple way to do it can be:
System.out.println("Hello world!".split(" ")[0]);
// Taking 'str' as your string
// To remove the first space(s) of the string,
str = str.trim();
int index = str.indexOf(" ");
String word = str.substring(0, index);
This is just one method of many.
str = str.replaceAll("\\s+", " "); // This replaces one or more spaces with one space
String[] words = str.split("\\s");
String first = words[0];
The simplest solution in my opinion would be to just locate the index which the user wants it to be cut off at and then call the substring() method from 0 to the index they wanted. Set that = to a new string and you have the string they want.
If you want to replace the string then just set the original string = to the result of the substring() method.
Link to substring() method: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int,%20int)
There are already 5 perfectly good answers, so let me add a sixth one. Variety is the spice of life!
private static final Pattern FIRST_WORD = Pattern.compile("\\S+");
public static String firstWord(CharSequence text) {
Matcher m = FIRST_WORD.matcher(text);
return m.find() ? m.group() : "";
}
Advantages over the .split(...)[0]-type answers:
It directly does exactly what is being asked, i.e. "Find the first sequence of non-space characters." So the self-documentation is more explicit.
It is more efficient when called on multiple strings (e.g. for batch processing a large list of strings) because the regular expression is compiled only once.
It is more space-efficient because it avoids unnecessarily creating a whole array with references to each word when we only need the first.
It works without having to trim the string.
(I know this is probably too late to be of any use to the OP but I'm leaving it here as an alternative solution for future readers.)
This would be more efficient
String str = "Hello world!";
int spaceInd = str.indexOf(' ');
if(spaceInd != -1) {
str = str.substring(0, spaceInd);
}
System.out.println(String.format("[%s]", str));

How to split string in two parts

I'm retrieving Strings from the database and storing in into a String variable which is inside the for loop. Few Strings i'm retrieving are in the form of:
https://www.ppltalent.com/test/en/soln-computers-ltd
and few are in the form of
https://www.ppltalent.com/test/ja/aman-computers-ltd
I want split string into two substrings i.e
https://www.ppltalent.com/test/en/soln-computers-ltd as https://www.ppltalent.com/test/en and /soln-computers-ltd.
It can easily be separated if i would have only /en.
String[] parts = stringPart.split("/en");
System.out.println("Divided String : "+ parts[1]);
But in many of the strings it has /jr , /ch etc.
So how can I split them in two sub-strings?
You could perhaps use the fact that /en and /ja are both preceeded by /test/. So, something like indexOf("/test/") and then substring.
In your examples, it seems like you're interested in the very last part, which could be retrieved by lastIndexOf('/') for instance.
Or, using look-arounds you could do
String s1 = "https://www.ppltalent.com/test/en/soln-computers-ltd";
String[] parts = s1.split("(?<=/test/../)");
System.out.println(parts[0]); // https://www.ppltalent.com/test/er/
System.out.println(parts[1]); // soln-computers-ltd
Split on the last /
String fullUrl = "https:////www.ppltalent.com//test//en//soln-computers-ltd";
String baseUrl = fullUrl.substring(0, fullUrl.lastIndexOf("//"));
String manufacturer = fullUrl.subString(fullUrl.lastIndexOf("//"));

Java - Changing multiple words in a string at once?

I'm trying to create a program that can abbreviate certain words in a string given by the user.
This is how I've laid it out so far:
Create a hashmap from a .txt file such as the following:
thanks,thx
your,yr
probably,prob
people,ppl
Take a string from the user
Split the string into words
Check the hashmap to see if that word exists as a key
Use hashmap.get() to return the key value
Replace the word with the key value returned
Return an updated string
It all works perfectly fine until I try to update the string:
public String shortenMessage( String inMessage ) {
String updatedstring = "";
String rawstring = inMessage;
String[] words = rawstring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
for (String word : words) {
System.out.println(word);
if (map.containsKey(word) == true) {
String x = map.get(word);
updatedstring = rawstring.replace(word, x);
}
}
System.out.println(updatedstring);
return updatedstring;
}
Input:
thanks, your, probably, people
Output:
thanks, your, probably, ppl
Does anyone know how I can update all the words in the string?
Thanks in advance
updatedstring = rawstring.replace(word, x);
This keeps replacing your updatedstring with the rawstring with a the single replacement.
You need to do something like
updatedstring = rawstring;
...
updatedString = updatedString.replace(word, x);
Edit:
That is the solution to the problem you are seeing but there are a few other problems with your code:
Your replacement won't work for things that you needed to lowercased or remove characters from. You create the words array that you iterate from altered version of your rawstring. Then you go back and try to replace the altered versions from your original rawstring where they don't exist. This will not find the words you think you are replacing.
If you are doing global replacements, you could just create a set of words instead of an array since once the word is replaced, it shouldn't come up again.
You might want to be replacing the words one at a time, because your global replacement could cause weird bugs where a word in the replacement map is a sub word of another replacement word. Instead of using String.replace, make an array/list of words, iterate the words and replace the element in the list if needed and join them. In java 8:
String.join(" ", elements);

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