Add an array of strings into ArrayList
Hi Guys
I would like to add an array of strings into an ArrayList, which i have implemented by using the following code:-
String[] strReturnWords = getInput2(line);
List.add(strReturnWords);strReturnWords returns an array of Strings.
How do i retrieve the array of strings from the ArrayList. I have tried
String[i] strString = List.toString();Am i doing this correctly, are their any other ways??
Many thanks
Jason
That should work.NO. That wont work AT ALL.
This:
String[] arrayOfString = new String[listName.size()];Is not right. The number of elements in the list is MUCH different
then the size of the array which is an element in the list.
This:
arrayOfStrings[ i] = (String)listName.get(i);Will fail. The list contains an Object of StringArray not an Object of String.
import java.util.*;
public class StringList{
public static void main(String[] args){
String text = "this is some text";
String[] words = text.split("\\s+");
ArrayList list = new ArrayList();
list.add(words);
String[] array = (String[])list.get(0);
for(int i = 0; i < array.length; i++){
System.out.println("Word: " + array);
Similar Messages
-
Convert an array of strings into a single string
Hi
I am having trouble trying to figure out how to convert an array of strings into a single string.
I am taking serial data via serial read in a loop to improve data transfer. This means I am taking the data in chunks and these chunks are being dumped into an array. However I want to combine all elements in the array into a single string (should be easy but I can't seem to make it work).
In addition to this I would also like to then split the string by the comma separator so if any advice could be given on this it would be much appreciated.
Many Thanks
Ashley.Well, you don't even need to create the intermediary string array, right? This does exactly the same as CCs attachment:
Back to your serial code:
Why don't you built the array at the loop boundary? Same result.
You could even built the string directly as shown here.
Message Edited by altenbach on 12-20-2005 09:39 AM
LabVIEW Champion . Do more with less code and in less time .
Attachments:
autoindexing.png 5 KB
concatenate.png 5 KB
StringToU32Array.png 3 KB -
Would like some help converting an array of strings into multiple parsed string arrays
Hello everyone.
this is a very novice question and I sincerely apologize for that, but i need some direction!
i have an array of strings:
(('J01',), ('0', '0', '0', '1'))
(('J02',), ('0', '1', '0', '1'))
(('J03',), ('0', '0', '0', '0'))
ect...
i would like to know what are some of the best ways to gain access to this information (aka, parse it). The field lengths are not static and all those ones and zeros could very possibly be two digits at times (0 = off state, 1-100 = on state), so simply pulling characters out of a given position of the string will not always work.
what i would like to achieve is to make either separate arrays for each desirable element, eg:
array one:
J01
J02
J03
array two:
0
0
0
array three:
0
1
0
and so on.
or maybe even a matrix (if that’s feasible).
other than that I am totally up for suggestions!!
thank you very much,
Grant.Assuming fixed structure (not necessarily length of the different numbers or names).
-
How to Convert the Stream of strings into ArrayList Integer
I have a String st = "12 54 456 76ASD 243 646"
what I want to do is print it like this from the ArrayList<Integer>:
12
54
456
243
646
It should catch the "76ASD" exception as it contain String Character.
This is how I am doing, which it seems to work but when it reaches the 76ASD it catches the exception so it is not adding the rest to the Arraylist, therefore I could not print in sequence.
public static void main(String[] args) {
// TODO code application logic here
getDatas(testString);
for (int i = 0; i < at.size(); ++i) {
System.out.println(at.get(i));
private static ArrayList<Integer> getDatas(String aString) {
StringTokenizer st = new StringTokenizer(aString);
try {
while (st.hasMoreTokens()) {
String sts = "";
sts = st.nextToken();
at.add(Integer.parseInt(sts));
} catch (Exception e) {
System.out.println("Error: " + e);
return at;
}Please guide me where I am going
Thankspaulcw wrote:
This is one of the few cases where I'd say catching an exception as part of the design is acceptable. When parsing, either something parses, or it doesn't. Using parseInt, we're parsing the string and using the result of the parse. By using a regular expression, we're parsing it twice, in two different ways, which may get out of sync. Not only that, if you have a more complicated case, like negative numbers and decimals, the regex gets really ugly.
I agree this is exactly the case where it is appropriate to try, catch, handle, move on. I sometimes wish there were an Integer.isValid(String) method, but even if there were, we'd call it, and if it returned true, we'd then call parseInt anyway, which would repeat the same work that isValid did. All it would buy us would be an if test instead of a try/catch. -
How to split an array (*not String*) into smaller arrays?
Hello,
let's say you have an array of bytes whith length (for example) 5000B. Now you want to split this array into smaller ones, for example 1500B. Then you will have 3 arrays of 1500B and another one of 500B. What I try to do then is the following:
pointer = 0;
size = source.length; // For example, size = 5000
maxsize = 1500;
while ((size - pointer) > maxsize) {
byte[] dest = new byte[maxsize];
System.arraycopy(src, pointer, dest, pointer, maxsize); // <--- Errors here!
pointer += maxsize;
// Do some stuff here with the dest array
}There's no errors at compile time. But at runtime, the first iteration everything works OK (the 1500 first bytes are copied to the dest array). However, in the second iteration, the java interpreter claims:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
at java.lang.System.arraycopy(Native Method)And I don't know what I'm doing bad. I guess there's a stupid question I can't see by myself... Help wanted, please!> System.arraycopy(src, pointer, dest, pointer, maxsize);should be
System.arraycopy(src, pointer, dest, 0, maxsize);Since you're copying to the first position in the destination array. -
Reading into ArrayList problem - what is wrong?
Hi, I am trying to read a list of strings into an ArrayList and am having some problems. I have created a main() which at the moment does nothing, its just to make sure that the array's content is genuine (meaning consistent with the string in the text file) so I am having it simply printed out to screen. The error I am getting is "cannot resolve symbol, variable array" by my compiler (Jcreator). I will paste the code below:
import java.io.*;
import java.util.*;
public class hostList{
public hostList()
try
File input = new File("hosts.txt");
BufferedReader in=new BufferedReader(
new InputStreamReader(new FileInputStream(input)));
ArrayList list=new ArrayList();
String line;
while((line=in.readLine())!=null)
list.add(line);
String[] array=new String[list.size()];
list.toArray(array);
in.close();
catch(FileNotFoundException e)
System.err.println("File not found...");
catch(IOException e)
System.err.println("IO Problem");
}//hostLst()
public static void main (String [] args){
System.out.println("Array content:");
System.out.println("array " + array[0]);
for (int i=0; array[i] !=null; i++)
System.out.println(array);
}//main
}//class
Also, how would I use the array objects in another class, say class B. How can I access the arrays in class B so that i can use its methods? eg. array[i].doSomething(); where doSomething() is a method in class B. What libraries would i need to import (if any) ?
Help is appreciated, thanks.this code wont compile bcas in main method u r not creating the object of this class also the var array is not globally declared hence wont be accesibile outside
u can try this modified code
import java.io.*;
import java.util.*;
public class hostList{
String[] array=null;
public hostList()
try
File input = new File("hosts.txt");
BufferedReader in=new BufferedReader(
new InputStreamReader(new FileInputStream(input)));
ArrayList list=new ArrayList();
String line;
while((line=in.readLine())!=null)
list.add(line);
array=new String[list.size()];
list.toArray(array);
in.close();
catch(FileNotFoundException e)
System.err.println("File not found...");
catch(IOException e)
System.err.println("IO Problem");
}//hostLst()
public static void main (String [] args){
hostList h=new hostList();
System.out.println("Array content:");
System.out.println("array " + h.array[0]);
}//main
}//class -
How to shrink an array of strings
I am working on the method shift() which is similar to the one found in Perl. This method will take an array of strings and return the first string in the array. The resulting array should shrink by one element.
However, I am having trouble with getting the array modified.
I will show the output and the code.
java DemoShift a b c
Args len: 3 Argument #0: a
bcc
Args len: 3 Argument #1: b
ccc
Args len: 3 Argument #2: c
ccc
As you can see, I expect the array to get smaller each time, but I was unsuccessful. I have tried the following approaches:
1. Convert the array of strings into StringBuffer by using append() and adding some delimeter, and then then using toString().split()
2. Use ArrayList class to change the array length
3. System.arraycopy.
Here is the code. Let me know what do I need to get the array "args" get shrinked every time.
<pre>
import java.util.*;
import java.io.*;
class DemoShift
public static void main(String args[])
for (int counter = 0; counter < args.length ; counter++)
System.out.println("Args len: " + args.length + " Argument #" + counter + ": " + shift(args));
for (String st:args) System.out.print (st);
System.out.println();
public static String shift(String... args)
StringBuilder sb = new StringBuilder(args.length-1);
String firstString = args[0];
String temp[] = new String[args.length -1];
for (int counter = 1; counter < args.length; counter++)
sb.append(args[counter]);
sb.append("MYSPLIT");
temp = sb.toString().split("MYSPLIT");
System.arraycopy(temp, 0, args, 0, temp.length);
return firstString;
}Edited by: vadimsf on Oct 25, 2007 10:17 PMI didn't really pay much attention to your problem, but will this help?
public static void main(String[] args) {
String[] test = {"test1", "test2", "test3"};
for (String s : shift(test))
System.out.println(s);
public static String[] shift(String[] arr)
String[] a = new String[arr.length - 1];
for (int i = 1; i < arr.length; i++)
a[i - 1] = arr;
return a; -
Arrray of strings into spreadsheet
hi,
Pls help me in writng the array of strings into spreadsheet (.xls)
I have 3 or 4 different 1d array of strings and i have to put each array of string into differnet coloumn....
thanksDoes it have to be an actual xls file or will a CSV (which can be read directly from Excel) file do?
If a CSV will work, combine all of the arrays into a 2D array. You will likely need to use Transpose 2D Array. Then use Array to Spreadsheet String with a comma as the delimiter. Write the new string to a text file.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines -
Split string into an array (Skip first character)
I have a string like:
,open,close,open
I want to parse the data into an array (without the first ','). I found and tweaked the following code, but the result was:
+<blank line> (think this is coming from the first ',')+
off
on
off
FUNCTION SPLIT (p_in_string VARCHAR2, p_delim VARCHAR2) RETURN t_array
IS
i number :=0;
pos number :=0;
lv_str varchar2(50) := p_in_string;
strings t_array;
BEGIN
-- determine first chuck of string
pos := instr(lv_str,p_delim,1,1);
-- while there are chunks left, loop
WHILE ( pos != 0) LOOP
-- increment counter
i := i + 1;
-- create array element for chuck of string
strings(i) := substr(lv_str,1,pos-1);
-- remove chunk from string
lv_str := substr(lv_str,pos+1,length(lv_str));
-- determine next chunk
pos := instr(lv_str,p_delim,1,1);
-- no last chunk, add to array
IF pos = 0 THEN
strings(i+1) := lv_str;
END IF;
END LOOP;
-- return array
RETURN strings;
END SPLIT;
I am working on a 9i database.How is your collection defined? Assuming you are doing something like
SQL> create type t_array as table of varchar2(100);
2 /
Type created.then you would just need to add an LTRIM to the code that initializes LV_STR and add appropriate EXTEND calls when you want to extend the nested table
SQL> ed
Wrote file afiedt.buf
1 create or replace FUNCTION SPLIT (p_in_string VARCHAR2, p_delim VARCHAR2)
2 RETURN t_array
3 IS
4 i number :=0;
5 pos number :=0;
6 lv_str varchar2(50) := ltrim(p_in_string,p_delim);
7 strings t_array := t_array();
8 BEGIN
9 -- determine first chuck of string
10 pos := instr(lv_str,p_delim,1,1);
11 -- while there are chunks left, loop
12 WHILE ( pos != 0)
13 LOOP
14 -- increment counter
15 i := i + 1;
16 -- create array element for chuck of string
17 strings.extend;
18 strings(i) := substr(lv_str,1,pos-1);
19 -- remove chunk from string
20 lv_str := substr(lv_str,pos+1,length(lv_str));
21 -- determine next chunk
22 pos := instr(lv_str,p_delim,1,1);
23 -- no last chunk, add to array
24 IF pos = 0
25 THEN
26 strings.extend;
27 strings(i+1) := lv_str;
28 END IF;
29 END LOOP;
30 -- return array
31 RETURN strings;
32* END SPLIT;
SQL> /
Function created.
SQL> select split( ',a,b,c', ',' ) from dual;
SPLIT(',A,B,C',',')
T_ARRAY('a', 'b', 'c')If T_ARRAY is defined as an associative array, you wouldn't need to have the EXTEND calls but then you couldn't call the function from SQL.
Justin -
How can i store values from my String into Array
Hi guys
i wants to store all the values from my string into an array,,,, after converting them into intergers,,,, how i can do this becs i have a peice of code which just give me a value of a character at time,,,,charat(2)...BUT i want to the values from String to store in an Array
here is my peice of code which i m using for 1 char at time
int[] ExampleArray2 = new int[24];
String tempci = "Battle of Midway";
for(int i=0;i>=tempci.length();i++)
int ascii = tempci.charAt(i); //Get ascii value for the first character.public class d1
public static final void main( String args[] )
int[] ExampleArray2 = new int[24];
String tempci = "Battle of Midway";
for(int i=0;i<tempci.length();i++)
int ascii = tempci.charAt(i);
ExampleArray2=ascii;
for(int i=0;i<ExampleArray2.length;i++)
System.out.println(ExampleArray2[i]); -
Is there an easy way to convert a long string into an array?
I can convert a long string into a 1-d array by parsing and using build array, but I would like to know if there is a function to make this easier.
For example:
from/ aaaaaaaabbbbbbbbccccccccdddddddd (string of ascii)
to/ an array that is 1-d with each element having eight characters
aaaaaaaa
bbbbbbbb
cccccccc
dddddddd
Thank you.
Solved!
Go to Solution.Try something like this:
(If you can guarantee that the string length is an integer multiple of 8, you an drop the two triangular modes in the upper left. )
Message Edited by altenbach on 03-14-2010 06:40 PM
LabVIEW Champion . Do more with less code and in less time .
Attachments:
ChopString.png 9 KB -
How to put a String into a byte array
How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David
javadocs for String
getBytes
public byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
Returns:
The resultant byte arraySince:
JDK1.1 -
Add Array grid report into Layout/tab ExtJS?
How to add Array grid report into Layout/tab ExtJS?
Array grid examples are from >
http://apex.oracle.com/pls/apex/f?p=43040:4:467728553403435
js>
Ext.onReady(function(){
4
5var munkyData = [
6
7["7369","SMITH","CLERK","7902","17-DEC-80","800"," ","20"]
8,["7499","ALLEN","SALESMAN","7698","20-FEB-81","1600","300","30"]
9
10,["7521","WARD","SALESMAN","7698","22-FEB-81","1250","500","30"]
11
12,["7566","JONES","MANAGER","7839","02-APR-81","2975"," ","20"]
13
14,["7654","MARTIN","SALESMAN","7698","28-SEP-81","1250","1400","30"]
15
16,["7698","BLAKE","MANAGER","7839","01-MAY-81","2850"," ","30"]
17
18,["7782","CLARK","MANAGER","7839","09-JUN-81","2450"," ","10"]
19
20,["7788","SCOTT","ANALYST","7566","09-DEC-82","3000"," ","20"]
21
22,["7839","KING","PRESIDENT"," ","17-NOV-81","5000"," ","10"]
23
24,["7844","TURNER","SALESMAN","7698","08-SEP-81","1500","0","30"]
25
26,["7876","ADAMS","CLERK","7788","12-JAN-83","1100"," ","20"]
27
28,["7900","JAMES","CLERK","7698","03-DEC-81","950"," ","30"]
29
30,["7902","FORD","ANALYST","7566","03-DEC-81","3000"," ","20"]
31
32,["7934","MILLER","CLERK","7782","23-JAN-82","1300"," ","10"]
33
34];
35
36var store = new Ext.data.SimpleStore({
37 el: store,
38 fields: [
39 {name: 'empno', mapping: '0'},
40 {name: 'ename', mapping: '1'},
41 {name: 'job', mapping: '2'},
42 {name: 'mgr', mapping: '3'},
43 {name: 'hiredate', mapping: '4'},
44 {name: 'sal', mapping: '5'},
45 {name: 'comm', mapping: '6'},
46 {name: 'deptno', mapping: '7'}
47 ]
48 });
49
50store.loadData(munkyData);
51
52var grid = new Ext.grid.GridPanel({
53 el: grid,
54 store: store,
55 columns: [
56 {id:'empno',header: "Employee",sortable:true, width:100,dataIndex:'empno'},
57 {header: "Name", sortable:true,width:75, dataIndex:'ename'},
58 {header: "Job", sortable:true, dataIndex:'job'},
59 {header: "Manager", sortable:true,width:75, dataIndex:'mgr'},
60 {header: "Hire Date", sortable:true,dataIndex:'hiredate'},
61 {header: "Salary", sortable:true,width:50,dataIndex:'sal'},
62 {header: "Commission", sortable:true,dataIndex:'comm'},
63 {header: "Department", dataIndex:'deptno'}
64 ],
65 stripeRows: true,
66 width:700,
67 autoHeight:true,
68 title:'Array Grid'
69 , renderTo: 'munkyDiv'
70 });
71});
any references?
regards
GordanHi Mark,
thanks for reply, I was making example on
http://apex.oracle.com/pls/otn/f?p=43048:22:2659745156195172
using debug grid layout and put into REGION_05
...< div id = "munkyDiv" > #REGION_POSITION_O5# < / div>
in this way I can add 1,2,3 or more reports as tab and grid.
Simple example as first step is basic layout (integration ExtJS and Apex)>
http://apex.oracle.com/pls/otn/f?p=43048:15
username/pass EXTJS/EXTJS
regards
Gordan
Edited by: useruseruser on Aug 8, 2010 2:51 PM
Edited by: useruseruser on Aug 8, 2010 2:52 PM -
"converting strings into integers in a array"
I'm really left scrating my head trying to figure this out.
What I have right now is this
public class NameManager
private names[] collection; // collection of names
private int count;
public NameManager() // Creating an array which for now is empty
collection = new names[1000];
count = 0;
String [] collection = {"boston", "Springfield", "New Haven",
"New York", "Albany"};
Its a namemanager for my road trip project which will be sort of like mapquest. What it does, or it's supposed to do is I have a array of names of cities, that represented as strings, in a array called, collection. What my proffeser wants me to do is turn the strings into integers, so in this elements in the array can be referenced .
It's probably so easy that I'll want to kick myself when I find out how to do it , but for whatever reason , all the information have found on the internet seems to go right over
If any body can give some idea of how to turn the string you see above into a set of intege s I would be so grateful.turn the string into the index in the array
i.e.
boston => 0
springfield => 1
New Haven => 2
New York => 3
Albany => 4I should've mention this before but I need the names to go along with the numbers.
This is the directions from my proffesser, I know it's not the easiest to understand
but hopefully It will give you a better idea of what I'm talking about.
A name manager. This object turns strings into numbers. Every time a name is added to the name manager, it is checked to see if it has already been seen. If so, return the number previously assigned to the name. If not, increment the "number of known names" and return this number as well as remember the string for future reference. You can assume that there will be no more than 1000 names in the manager. Each name is a string.
A city. A city is a simple object: the city has a name and a number (at present).
I got most of this part done it just strings integers part that's getting me. -
How do I split a comma delimited string into an array.
I have a string that I am passing into a function that is Comma delimited. I want to split the string into an array. Is there a way to do this.
Thanks in advance.trouble confirmed on 10gR1 and 10gR2
works with 'a,b,c' and also with ' "1" , "2" , "3" '
does not work with '1,2,3'
throwing ORA-6512
Maybe you are looking for
-
StorLib error message in the Lenovo Solution Center
I keep getting an error message under the device manager tab in the Lenovo Solution Center. It says under drivers - 'StorLib bus (virtualstorage support)', status is 'Uninstalled'. I can't find anything anywhere about this or how to correct the issue
-
Hi, I just read an article on BI Tools vendor share by revenue, done by IDC. It has some interesting numbers, and this article is currently posted on IDC, Intelligent Enterprise, and SAS website. Top 5 BI tools Revenue by Vendor: 1. Business Objects
-
Poor Image Quality when printing in Pages
I created small (150 x 100 pixel at 72 dpi) images for printing on a one-page flyer in Pages. I dragged and dropped them into place, and things look great on the monitor. But when I print (using a Canon MX310) all-in-one, the images look bad - they a
-
IMovie crashes soon after loading
I'm new here, and I'm kinda new with iMovie. I've been working on a 7 minute project with some friends, doing some voiceovers and adding in audio tracks. As we added in audio tracks it seemed to be getting a bit slower and less responsive, but it was
-
CAN ANYBODY REPLY TO THIS QUESTION : Mike Keller did a period billing for WBS 2008044-MO & 2008052-MO Jan 2 through Feb 29. The Invoices had to be cancelled because of the wrong Tax Code. Mike cannot perform another DP91 for the same period. How does