I wish to get the specific element named Something in a string within a String[] for JAVA.
My code =
String sentence = "AP=Something+example|AS=Explanation";
String[] word = sentence.split("\\|");
for (String w: word){
System.out.println(w);
}
My current output:
AP=Something+example
AS=Explanation
My expected output should be:
Something // the other information I dont want to take. Is there a better and faster way and not too time consuming?
Thank you in advance
If you want to split on plus not pipe then change
String[] word = sentence.split("\\|");
to
String[] word = sentence.split("\\+");
I don't understand what you really want, but:
String sentence = "AP=Something+example|AS=Explanation";
String[] recs = sentence.split("\\|");
HashMap<String, String> h = new HashMap<String,String>();
for (String r : recs) {
String[] vals = r.split("=");
h.put(vals[0], vals[1]);
}
System.out.println(h.get("AP").split("\\+")[0]);
This code is so bad, but look at common idea.
My english so bad too.
Related
I am new to java . I have this String.
str="plane,cat,red,dogy";
I want to make a loop and send the data . the below is wrong but i want something similar to it.
for ( int i = 0; i>str.length; i++)
{
str=split.string(,);
// i know it wrong but I want to get the result before comma, for example first loop plane, second loop cat third loop red and so on
updatestatement(str);
}
This should be what you are looking for:
String str="plane,cat,red,dogy";
for(String subString: str.split(",")){
updatestatement(subString);
}
String[] words= str.split(",");
for (String w : words){
//Do whatever you want with each word
}
Don't use for to split. Just:
String[] parts = str.split(",");
It is very unclear what you need. But i think you are looking for this:
String[] s = str.split(",");
for ( int i = 0; i<s.length; i++)
{
// i know it wrong but I want to get the result before comma, for example first loop plane, second loop cat third loop red and so on
updatestatement(str);
}
Where updatestatement is a method in your class
The answer is simple.
String str="plane,cat,red,dogy";
String[] items = str.split(",");
System.out.println("No of items::"+items.length);
If you want to print each item,
for (String eachItem : items) {
System.out.println(eachItem);
//updateStatement(eachItem);
}
You should do it as follows :
String str="plane,cat,red,dogy";
String[]str1=str.split(",");
for ( int i = 0; i>str1.length; i++)
{
updatestatement(str1[i]);
}
String str="plane,cat,red,dogy";
String[] parts = str.split(",");
Arrays.stream(parts).forEach(System.out::println);
This solution only works with Java 8 because of the stream method. If you remove the last line it also works with other Java versions.
I'm sure this is a fairly easy question for someone but I cant work out the best way to do it as a relative beginner.
I am splitting a large file (the string temp) into about a 100 strings and setting it as an array, but I don't know the exact number of strings.
String[] idf = temp.split("===========");
String class1 = idf[0];
String class2 = idf[1];
String class3 = idf[1];
etc etc..
What is the best way to ensure that I can split all the strings and store them in an array?
Any suggestions or pointers would be most appreciated thanks!
You can do it like this:
String list = "hey there how are you";
String[] strarray = list.split("\\s+");
for (String str: strarray)
{
System.out.print(str);
}
Probably you want to iterate over your String array.
You can do it like that:
for(String s : idf) {
//operate on s here
}
Use for-each to get elements from array.
Please look at oracle official site for for-each loop.
Consider below code.
String tempString = "";
String regex = "";
String[] temparray = tempString.split(regex);
for (String temp : temparray)
{
System.out.println(temp);
}
I want to evaluate String like "[1,5] [4,5] [10,6]" in in array.
I'm not quite familiar with the Java regex and the syntax.
String game = "[1,5] [4,5] [10,6]"
Pattern splitter = Pattern.compile("\\[|,|\\]");
splitter.matcher(game);
public String [] gameArray = null;
gameArray = splitter.split(game);
I want to to iterate over each pair of array such as : [0][0] => 1; [0][1] => 5
If you put
StringTokenizer st = new StringTokenizer(game, "[,] ");
while (st.hasMoreTokens())
{
currentNumber = Integer.parseInt(st.nextToken());
// fill array with it
}
It should be what you need, if I understood well
For this purpose you need to split your string.
first of all you need to split on space and after that you need to split on ,(comma).and your third step will be remove brackets So at the end you will get you string into array.
Try,
String game = "[1,5] [4,5] [10,6]";
String[] arry=game.substring(1, game.length()-1).split("\\] +\\[");
List<String[]> twoDim=new ArrayList<>();
for (String string : arry) {
String[] twoArr=string.split(",");
twoDim.add(twoArr);
}
String[][] twoArr=twoDim.toArray(new String[0][0]);
System.out.println(twoArr[0][0]); // 1
System.out.println(twoArr[0][1]); // 5
I have a String :
str="[a],[b],[c]";
How can I convert str to array in Java (Android):
array[0] -> a
array[1] -> b
array[2] -> c
EDIT:
and what about multidimensinal array? str="[["a1","a2","a3"],["b1","b2","b3"]]";
try
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");
===========================================
update
converting multi dimension array to single dimension is already answered in SO please check change multidimensional array to single array
just copied the solution
public static String[] flatten(String[][] data) {
List<String> toReturn = new ArrayList<String>();
for (String[] sublist : Arrays.asList(data)) {
for (String elem : sublist) {
toReturn.add(elem);
}
}
return toReturn.toArray(new String[0]);
}
You can use following way.
String Vstr = "[a],[b],[c]";
String[] array = Vstr.replaceAll("\\]|\\[", "").split(",");
You would need to process your string and build your array. You could either take a look at .split(String regex) (which might require you to do some more processing to clean the string) or else, use a regular expression and do as follows:
Use a regex like so: \[([^]]+?)\]. This will seek out characters in between square brackets and put them into a group.
Use the .find() method available from the Matcher class and iterate over the matches. Put everything into a list so that you can put in as many hits as you need.
If you really need the result to be in an array, use the .toArray() method.
Take a look at String.split() method
An alternative to the regex and what npinti, i think, is talking about:
String myStrg = "[a],[b],[c]";
int numCommas = 0;
for( int i = 0; i < myStrg.length(); i++ )
{
// Count commas
if( myStrg.charAt(i) == ',' )
{
numCommas++;
}
}
// Initialize array
myArry = new String[numCommas];
myArry = myStrg.split(",");
// Loop through and print contents of array
for( String arryStrg: myArry )
{
System.out.println( arryStrg );
}
Try this code.
String str="[a],[b],[c]";
str= str.replaceAll("\\]|\\[", "");
String[] arr= str.split(",");
I have a text file that contains information formated in a key=value way. How do I look up the key and return the value.
For example, let's say the file has:
KeyOne=ValueOne
KeyTwo=ValueTwo
and I would like to have a method which takes KeyOne and returns ValueOne.
Okay, I'm in a good mood :), untested:
//given that 'input' got the contents of the file
Map<String,String> m = new HashMap<String,String>();
//this can be done more efficient probably but anyway
//normalize all types of line breaks to '\n'
input = input.replaceAll("\r\n","\n");
input = input.replaceAll("\r","\n");
//populate map
String[] lines = input.split("\n");
for(int i=0 ; i< lines.length; i++){
String[] nv = lines[i].split("=");
m.put(nv[0],nv[1]);
}
//get value given key:
String key = "somekey";
String someValue = m.get(key);
System.out.println(someValue);
Scanner s = new Scanner("Filename");
Map<String, String> m = new HashMap<String, String>();
while(s.hasNext()){
String line[] = s.nextLine().split("=");
m.put(line[0], line[1]);
}
To get the value:
m.get(ValueOne);
In case all you need is to read name-value pairs, and if that is of configuration nature, then you can consider using properties file in Java.
You can check this out http://www.mkyong.com/java/java-properties-file-examples/
Whole bunch of ways. You could
a. Read the file once line by line, split the input and then populate a map
b. Apply a regex expression search to the file as a whole
c. You could index a full text search the thing
It all depends on your use case. Hard to recommend an approach without understanding the context.