There is a long string- "sourceMeaning" which consists of some sentences retrieved from a SQLiteDatabase. I used "&" to separate the sentences like below:
SentenceA&SentenceB&SentenceC .....
After the long string has been retrieved, the string will be divided to:
SentenceA
SentenceB
SentenceC
....
I used a String array (Meanings) to store the divided sentences and applied the following codes to finish the task, but it throws StringIndexOutOfBoundsException when executing...
String sourceMeaning=c.getString(1);
Log.w("SourceMeaning",sourceMeaning);
String[] Meanings=new String[]{};
int j=0;
for (int i=0;i<=sourceMeaning.length();i++){
if (sourceMeaning.charAt(i)!='&'){
Meanings[j]=Meanings[j]+sourceMeaning.charAt(i);
Log.w("Translated",Meanings[j]);
} else {
j+=1;
}
}
How to divide the sentences without error?
You can use the split() and then iterate through the generated array:
String[] sentences = sourceMeaning.split("&");
for (String sentence: sentences) {
//iterate through each one of the sentences, i.e:
//SentenceA, SentenceB, ....
}
you should split the initial string in this way
String sourceMeaning=c.getString(1);
Log.w("SourceMeaning",sourceMeaning);
String[] meanings = sourceMeaning.split("&");
you will have everything in that array
i'm not sure to totally get what you are trying to do, so i'm gonna answer this question:
How to divide the sentences without error?
Using the split method of the String Class in Java
Here
You can use str.split() method to get your string to array like :
String[] Meanings = sourceMeaning.split("&");
Related
I know the normal one to split the sentence by using split function, but the problem is you need to declare how many variables you need,
Example: Fighting,Action,Adventure,Racing,RPG
String[] GameGenreCodeSeparated = GameGenreCodeRAW.split(",");
listGameGenre.add(GameGenreCodeSeparated[0]);
listGameGenre.add(GameGenreCodeSeparated[1]);
listGameGenre.add(GameGenreCodeSeparated[2]);
How to add a list every ',' symbol, so a list can has 5 objects from that sentence dynamically, any solution?
You would want to iterate through your array. Something like the below should work.
String[] GameGenreCodeSeparated = GameGenreCodeRAW.split(",");
for (String GameGenre: GameGenreCodeSeparated ) {
listGameGenre.add(GameGenre);
}
Use built-in method Arrays.asList(GameGenreCodeRAW.split(",")) to avoid manually adding.
#Sungakki You should check which approach is better and in this case, Arrays.asList(GameGenreCodeRAW.split(",")) looks better approach which can help you in the future as well.
The reason is Arrays.asList() is a standard utility method for dealing with Arrays. Writing custom for() loop makes no sense here.
If you are having difficulty in understanding what it is doing them below is further details on this.
Here is how you will use it in your code.
listGameGenre = Arrays.asList(GameGenreCodeRAW.split(","));
Arrays.asList() simply returns a fixed-size list backed by the specified array in our case it is GameGenreCodeRAW.
Here is the official documentation for Arrays.asList() official docs.
I hope you understand my point.
It's better to create a new array or an arraylist because it's gonna be a hot mess trying to split a string but not store any data anywhere else.
Here is how I think it should be:
import java.util.ArrayList;
public class test
{
public static void split(String raw){
ArrayList <String> GameGenreCodeSeparated= new ArrayList<String>();
int splits=0;//how man times have the sentence been splited
int previousSplited=0;//index of the prevoius comma
for(int i=0;i<raw.length();i++){
if(raw.charAt(i)==','){//when comma occurs
if(previousSplited==0){//if this is the first comma
GameGenreCodeSeparated.add(raw.substring(0,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
else{
GameGenreCodeSeparated.add(raw.substring(previousSplited+1,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
}
else if (i==raw.length()-1){//if this is the end of the string
GameGenreCodeSeparated.add(raw.substring(previousSplited+1,i));//add the splited string to the list
previousSplited=i;//record the place where splited
}
}
System.out.println(GameGenreCodeSeparated);//print out results;
}
}
Hope this helps!
String text = "In addition, Androids could multitask, whereas iPhones could not at that time. By 2011, Android outsold every other smartphone";
String[] textSeparated = text.split(",");
String first=textSeparated[0];
String second=textSeparated[1];
String Third=textSeparated[2];
String Fourth=textSeparated[3];
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.
My arraylist consists of an array with a list of strings, each string inside is separated by commas, i want to split one of the strings into substrings divided by the commas, i know how to do it to arrays by using the split method, but im having trouble finding something similar to array lists, heres the code:
String[] widgets2 =
{
"1,John,Smith,John1989#gmail.com,20,88,79,59",
"2,Suzan,Erickson,Erickson_1990#gmailcom,19,91,72,85",
"3,Jack,Napoli,The_lawyer99yahoo.com,19,85,84,87",
"4,Erin,Black,Erin.black#comcast.net,22,91,98,82",
"5,Adan,Ramirez,networkturtle66#gmail.com,100,100,100"
};
ArrayList<String> jim = new ArrayList<String>(Arrays.asList(widgets2));
System.out.println(jim.split(0));
It is similar to what you do with the arrays. Just that the implementation is different. To get the values just loop through them:
List<String> jim = new ArrayList<String>(Arrays.asList(widgets2));
for(String currentString : jim){//ArrayList looping
String[] separatedStrings = currentString.split(",");
for(String separatedString : separatedStrings){//Now its array looping
//Do something now whatever you like to
}
}
If you want to have the index and decide which value to get, use normal for loop using index and use jim.get(index) and use split().
Having said that, what stops you from looping through the List ? It's the common usage of array list - to loop through it :)
String jim_string = jim.toString().replace("[", "");
jim_string.replace("]", "");
String splitted[] = jim_string.split(",");
System.out.println(splitted[0]);
put the below code lines into your code, it'll give your desire output.
int indx=0; //use the index you want to get & split
String tmp = jim.get(indx); // get the string from the ArrayList
if(tmp!=null && !tmp.equals("")){ // null check
for (String retval: tmp.split(";")){ // split & print
System.out.println(retval);
}
}
I'm a computer science student learning Java, and as an exercise, we're doing a permutation algorhythm.
Now, i'm stuck at a point where i need to search for a natural number within a String full of numbers, splitted by a comma:
String myString = "0,1,2,10,14,";
The problem is i'm using...
myString.contains(String.valueOf(anInteger);
...to check for the presence of a specific number. This works for numbers from 0 to 9, but when looking for a more-than-1-digit number, the program does not recognize it as a natural number.
In other words, and as an example: "14" is not the integer 14, its just a string with an "1", and a "4"; so, if i run...
String myString = "0,1,2,10,14,";
if (myString.contains(myString.valueOf(4))) { doSomething(); }
...the "if" statement will be true, since the integer "4" is present in the string, as part of the natural number "14".
At this point, i've been searching through StackOverflow and other pages for a solution, and learnt i should use Pattern and Matcher.
My question is: what's the best way to do use them?
Relevant part of my code:
for (int i = 0; i<r; i++)
{
if (!act.contains(String.valueOf(i)))
{
...
}
...
}
I use this method several times in my code, so an exact substitution would be nice.
Thank you all in advance!
You only need a method call to matches():
if (myString.matches(".*\\b" + anInteger + "\\b.*"))
// string contains the number
This works using by creating a regex that has a word boundary (\b) at either end of the target number. The leading and trailing .* are required because matches() must match the whole string to return true.
Look into how to split a String into an array of String. So:
String[] splitStrings = myString.split(",")
ArrayList<Integer> parsedInts = new ArrayList<Integer>();
for (String str : splitStrings) {
parsedInts.add(Integer.parseInt(str));
}
then in your for loop:
if (parsedInts.contains(i)) {
// body
}
Something like this:
String myString = "0,1,2,10,14,";
String[] split = myString.split(",");
for (String string : split) {
int num = Integer.parseInt(string);
if (num == 4) {
System.out.println(num);
// ...
}
}
String myString = "0,1,2,10,14,2323232";
String[] allList = myString.split(",");
for (String string : allList) {
if(string.matches("[0-9]*"))
{
System.out.println("Its number with value "+string);
}
}
I think you need to pick all the numbers in the given string and find the permutation.
I think you need to Tokenize the given string with the Comma Separator.
When I do such program, I divide my logic to parse the String and write the logic in another method. Below is the snippet
String myString = "0,1,2,10,14,";
StringTokenizer st2 = new StringTokenizer(myString , ",");
while (st2.hasMoreElements()) {
doSomething(st2.nextElement());
}
What I want to do is to measure the data of a line on a large string. I am not sure if any has tried this but I have a string which looks like this.
String a =
"This is
kinda
my String"
which would display on android textview as
This is
kinda
my String
Now what I want to achieve is being able get the length of the second line "kinda".
The purpose for this is to be able to set my paging for a book project.
I hope I was clear enough. Thanks for any advice or ideas shared.
Should just be:
a.split("\n")[1].length()
You can use the String function split(String regex)
To split on a "\n"(newline) then use it as a tuple/array and call for any word you want.
Split based on new line indicator.
String lines[] = a.split("\\r?\\n");
int length =0;
if(lines.length >1)
{
length = lines[1].length();
}
I haven't used java in years that being said I'd imagine something like this
String[] temp; //Let's make an array of strings
temp = a.split("\n"); //Split the large string by carriage return
int length = temp[1].length(); //get the length of the 2nd string
Assuming those are \n separating your lines...