How do i cut this out to 4 sentences instead of 1.
i need to cut it out to 4 sentence and only 4 because my jList only accept 4 "persons"
in the JList it stands like this
name,2,2,2,2
Lars,1,4,2,5
Peter,5,3,2,1
Code:
List listOfPersonNames = jListpersons.getSelectedValuesList();
// your list of strings
List<String> listOfNameStrings = new ArrayList<String>(listOfPersonNames.size());
for(Object personName: listOfPersonNames) {
listOfNameStrings.add(personName.toString());
}
// your string from the resulting list
String listString = listOfNameStrings.toString();
System.out.println(listString);
//con.saveTeamListFile();
}
I am not entirely sure on the question so I am going to assume that you need to split that string into elements such as Lars,1,4,2,5. In which case you can split at the space
String[] names = nameString.split(" ");
You may though be better off separating the elements with another character in case in you want to use strings with spaces in future
Related
I have s string in which * can come at arbitrary number. The regex pattern I use doesnt split at the beginning. I do not want to do the String.substring() to remove the * in the beginning. It can be that I have something like "***place1*place2**place3*". Or something like placeStr=**
String placeStr="*place1*place2**place3*";
String[] places=placeStr.split("(\\*)+");
System.out.println("array size" + places.length);
Also while using String.split("(\\*)+")to remove the placeStr=** gives a wrong array size if the input string is something like ***. In this case I get array size as one. But I expect array size to be zero, since there is no places inside the array. What I want to count is the number of places.
If you don't want to deal with empty strings while doing split in case there are multiple stars in the beginning, just replace the stars in beginning and then just do a simple split.
Sample code,
public static void main(String[] args) {
String placeStr = "***place1*place2**place3*";
placeStr = placeStr.replaceAll("^[*]+", "");
String[] places = placeStr.split("[*]+");
System.out.println("places.length: " + places.length);
Arrays.asList(places).forEach(System.out::println);
}
Prints,
places.length: 3
place1
place2
place3
Let me know if this is what you wanted to do.
Editing answer to clarify about split:
Considering your code,
String placeStr="*place1*place2**place3*";
String[] places=placeStr.split("(\\*)+");
System.out.println("array size: " + places.length);
You will get,
array size: 4
because the first star in the string splits and gives empty string. But if you remove all the stars in the beginning of string and make your code like this,
String placeStr="place1*place2**place3*";
String[] places=placeStr.split("(\\*)+");
System.out.println("array size: " + places.length);
Then this will output array size as,
array size: 3
The last star(s) (or any char) characters in the string does not behave like the first characters, and upon splitting, they don't give empty string in the last array elements.
This is how splitting a string by a regex works in java. Let me know if you had some other expectation, may be due to which you are saying it is giving you wrong output.
Hope this clarifies.
Also, can you let me know what you want to achieve logically?
I have two Strings with many words in it.
My task is to find the percentage of word match between two strings. Can someone suggest me the algorithm we already have to get precise percentage/matched word.
Example :
1. Mason natural fish oil 1000 mg omega-3 softgels - 200 ea
2. Mason Vitamins Omega 3 Fish Oil, 1000mg. Softgels, Bonus Size 200-Count Bottle
**Output** should be 8 words matched between two strings.
You can use method as below. I have added inline comments to discribe the each step you can try it. Note that on this code example I have used space character to split the words. If you have any concerns you can add comment.
Note that I have did the matching words ignoring the case because otherwise there was no possibility to have 8 matching words in your given example.
public static int matchStrings(String firstString, String SecondString) {
int matchingCount = 0;
//Getting the whole set of words in to array.
String[] allWords = firstString.split("\\s");
Set<String> firstInputset = new HashSet<String>();
//getting unique words in to set
for (String string : allWords) {
firstInputset.add(string);
}
//Loop through the set and check whether number of words occurrence in second String
for (String string : firstInputset) {
if (SecondString.toLowerCase().contains(string.toLowerCase())) {
matchingCount++;
}
}
return matchingCount;
}
Write a method that takes two parameters (1) the original string and (2) the word length and
returns a new string that contains the words of the specified length from the original string without
any duplicates. Here is an example of program execution:
getWordsOfLengthN(“We are the best, are we ?”, 3) “are the”
getWordsOfLengthN(“We are the best, are we ?”, 2) “we”
Notice that the method considers does not differentiate between the upper and lower cases.
Hint:
Tokenize string into an array of words
Change all the words to be become lowercase
Store all the words into a HashSet
Retrieve all the items from the HashSet and store them into the resulting string
I am new to java, I am taking an online course so everything I do know is self taught. I'm not sure how to go about this method, it is really stumping me. Can anyone offer me some ideas? Thanks
public static String getWordsOfLengthN(String originalString, int wordLegth) {
Set<String> hashSet = new HashSet<String>();
String[] words = originalString.split(" ");
for (String word : words) {
if(word.length() == wordLegth) {
hashSet.add(word);
}
}
return hashSet.toString();
}
I have a serious problem with extracting terms from each string line. To be more specific, I have one csv formatted file which is actually not csv format (it saves all terms into line[0] only)
So, here's just example string line among thousands of string lines:
(split() doesn't work.!!! )
test.csv
"31451 CID005319044 15939353 C8H14O3S2 beta-lipoic acid C1C[S#](=O)S[C##H]1CCCCC(=O)O "
"12232 COD05374044 23439353 C924O3S2 saponin CCCC(=O)O "
"9048 CTD042032 23241 C3HO4O3S2 Berberine [C##H]1CCCCC(=O)O "
I want to extract "beta-lipoic acid" ,"saponin" and "Berberine" only which is located in 5th position.
You can see there are big spaces between terms, so that's why I said 5th position.
In this case, how can I extract terms located in 5th position for each line?
One more thing: the length of whitespace between each of the six terms is not always equal. the length could be one, two, three, four, or five, or something like that.
Because the length of whitespace is random, I can not use the .split() function.
For example, in the first line I would get "beta-lipoic" instead "beta-lipoic acid.**
Here is a solution for your problem using the string split and index of,
import java.util.ArrayList;
public class StringSplit {
public static void main(String[] args) {
String[] seperatedStr = null;
int fourthStrIndex = 0;
String modifiedStr = null, finalStr = null;
ArrayList<String> strList = new ArrayList<String>();
strList.add("31451 CID005319044 15939353 C8H14O3S2 beta-lipoic acid C1C[S#](=O)S[C##H]1CCCCC(=O)O ");
strList.add("12232 COD05374044 23439353 C924O3S2 saponin CCCC(=O)O ");
strList.add("9048 CTD042032 23241 C3HO4O3S2 Berberine [C##H]1CCCCC(=O)O ");
for (String item: strList) {
seperatedStr = item.split("\\s+");
fourthStrIndex = item.indexOf(seperatedStr[3]) + seperatedStr[3].length();
modifiedStr = item.substring(fourthStrIndex, item.length());
finalStr = modifiedStr.substring(0, modifiedStr.indexOf(seperatedStr[seperatedStr.length - 1]));
System.out.println(finalStr.trim());
}
}
}
Output:
beta-lipoic acid
saponin
Berberine
Option 1 : Use spring.split and check for multiple consecutive spaces. Like the code below:
String s[] = str.split("\\s\\s+");
for (String string : s) {
System.out.println(string);
}
Option 2 : Implement your own string split logic by browsing through all the characters. Sample code below (This code is just to give an idea. I didnot test this code.)
public static List<String> getData(String str) {
List<String> list = new ArrayList<>();
String s="";
int count=0;
for(char c : str.toCharArray()){
System.out.println(c);
if (c==' '){
count++;
}else {
s = s+c;
}
if(count>1&&!s.equalsIgnoreCase("")){
list.add(s);
count=0;
s="";
}
}
return list;
}
This would be a relatively easy fix if it weren't for beta-lipoic acid...
Assuming that only spaces/tabs/other whitespace separate terms, you could split on whitespace.
Pattern whitespace = Pattern.compile("\\s+");
String[] terms = whitespace.split(line); // Not 100% sure of syntax here...
// Your desired term should be index 4 of the terms array
While this would work for the majority of your terms, this would also result in you losing the "acid" in "beta-lipoic acid"...
Another hacky solution would be to add in a check for the 6th spot in the array produced by the above code and see if it matches English letters. If so, you can be reasonably confident that the 6th spot is actually part of the same term as the 5th spot, so you can then concatenate those together. This falls apart pretty quickly though if you have terms with >= 3 words. So something like
Pattern possibleEnglishWord = Pattern.compile([[a-zA-Z]*); // Can add dashes and such as needed
if (possibleEnglishWord.matches(line[5])) {
// return line[4].append(line[5]) or something like that
}
Another thing you can try is to replace all groups of spaces with a single space, and then remove everything that isn't made up of just english letters/dashes
line = whitespace.matcher(line).replaceAll("");
Pattern notEnglishWord = Pattern.compile("^[a-zA-Z]*"); // The syntax on this is almost certainly wrong
notEnglishWord.matcher(line).replaceAll("");
Then hopefully the only thing that is left would be the term you're looking for.
Hopefully this helps, but I do admit it's rather convoluted. One of the issues is that it appears that non-term words may have only one space between them, which would fool Option 1 as presented by Hirak... If that weren't the case that option should work.
Oh by the way, if you do end up doing this, put the Pattern declarations outside of any loops. They only need to be created once.
e.g.:
If the number is 234, I would like the result to be List<String> containing 2,3,4 (3 elements)
If the number is 8763, I would like the result to be List<String> containing 8,7,6,3 (4 elements)
Does commons-math already have such a function?
Convert the number to a String (123 becomes "123"). Use Integer.toString.
Convert the string to a char array ("123" becomes {'1', '2', '3'}). Use String.toCharArray.
Construct a new, empty Vector<String> (or some other List type).
Convert each char in the char array to a String and push it onto the Vector ({'1', '2', '3'} becomes a Vector with "1", "2" and "3"). Use a for loop, Character.toString and List.add.
Edit: You can't use the Vector constructor; have to do it manually.
int num = 123;
char[] chars = Integer.toString(num).toCharArray();
List<String> parts = new Vector<String>();
for (char c : chars)
{
parts.add(Character.toString(c));
}
There isn't an easier way to do this because it really isn't a very obvious or common thing to want to do. For one thing, why do you need a List of Strings? Can you just have a list of Characters? That would eliminate step 3. Secondly, does it have to be a List or can it just be an array? That would eliminate step 4.
You can use the built in java.util.Arrays.asList:
int num = 234;
List<String> parts = Arrays.asList(String.valueOf(num).split("\\B"));
Step by step this:
Converts num to a String using String.valueOf(num)
Splits the String by non-word boundaries, in this case, every letter boundary except the start and the finish, using .split("\\B") (this returns a String[])
Converts the String[] to a List<String> using Arrays.asList(T...)
Arrays.asList( String.valueOf(number).toCharArray() )
Try this:
Arrays.asList(String.valueOf(1234).split("(?!^)"))
It will create list of Strings:
["1", "2", "3", "4"]
This seems like homework.
Consider using % and / to get each digit instead of converting the entire number to a String