Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-29-2011, 08:02 AM   PM User | #1
Scriptr
Regular Coder

 
Join Date: Oct 2011
Posts: 106
Thanks: 12
Thanked 0 Times in 0 Posts
Scriptr is an unknown quantity at this point
Split string ArrayList

I need to split a string. Simple:
Code:
String s = "Hello-world";
String str[] = new String[2];
str = s.split("-");
But, what happens when your string is user input?
Code:
String s = JOptionPane.showInputDialog(null, "text will be split at the spaces");
//they enter "Hello-world,-my-name-is-Susie"
String str[] = new String[2];
str = s.split("-");
This throws an out of bounds exception at 2.
What about ArrayList()?
Code:
//with the same user input
ArrayList<String> strings = new ArrayList<String>();
strings.add(s.split("-"));
The thing is that (for an ArrayList), there is no such thing as that last bit of code. What code that is real and does the job of strings.add(s.split("-")); for an ArrayList?
Scriptr is offline   Reply With Quote
Old 12-29-2011, 09:54 AM   PM User | #2
Apothem
Regular Coder

 
Apothem's Avatar
 
Join Date: Mar 2008
Posts: 380
Thanks: 36
Thanked 25 Times in 25 Posts
Apothem is an unknown quantity at this point
One solution is using an enhanced for loop:
for(String sub : s.split("-")) { strings.add(sub); }
Apothem is offline   Reply With Quote
Old 12-29-2011, 12:07 PM   PM User | #3
alykins
Senior Coder

 
alykins's Avatar
 
Join Date: Apr 2011
Posts: 1,608
Thanks: 37
Thanked 183 Times in 182 Posts
alykins will become famous soon enough
maybe something like this...
Code:
string splitme = ""; //use this string to accept arguments

.... elsewhere ...

int _chars = 1; 
if(splitme.length != 0){
for(int i = 0; i<=splitme.length; i++){
  char evalchar = splitme.charAt(i);
  if(evalchar == "-")
    _chars++;
}
}

string[] splitArray = new string[_chars];
... then do your split ...
so what is going on here (and it may be flawed a bit since my J skills are growing )
setting an int to be 1 by default so if the string contains no "split" char you don't end up trying to make a 0 length array- you will just get an array made with 1 spot; also your total amount of array that you will need to make will always be 1 more than how many split chars you have so it sets it up nicely.
next going to take the string and if it is not length 0 (ie "") going to go through it and (i<=splitme.length) count how many split variables there are by using the .charAt() method. this points to a place on the string and looks to see what that char is, if it is our split char then we increment how many array slots we will be making and if not we move on and do nothing.
__________________

I code C hash-tag .Net
Reference: W3C W3CWiki .Net Lib
Validate: html CSS
Debug: Chrome FireFox IE
alykins is offline   Reply With Quote
Old 12-29-2011, 01:47 PM   PM User | #4
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,653
Thanks: 4
Thanked 2,451 Times in 2,420 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
?
String.split will return an array; you don't need to predeclare an array size to overwrite:
PHP Code:
String[] str s.split("-"); 
Edit:
Oh, and if you want a list, that can be done by using Arrays.asList.
PHP Code:
List<Stringal Arrays.asList(s.split("-")); 

Last edited by Fou-Lu; 12-29-2011 at 01:52 PM..
Fou-Lu is offline   Reply With Quote
Users who have thanked Fou-Lu for this post:
Scriptr (12-29-2011)
Old 12-29-2011, 03:33 PM   PM User | #5
alykins
Senior Coder

 
alykins's Avatar
 
Join Date: Apr 2011
Posts: 1,608
Thanks: 37
Thanked 183 Times in 182 Posts
alykins will become famous soon enough
i thought in my other post you said you cannot do that in Java- in another thread I had posted (granted I was doing something different)
*sidebar - sorry OP I don't mean to hijack thread but I feel info that I am asking is relevant to you as well*
Ref thread
so i had (and it was in ref to ant int[] but I assume same issue would have happened for string[])
Code:
string[] validatethis = null;
and then later.....
validatethis = mystring.split(".");
So I assume that would have crashed out.. am I wrong on that assumption? or does it work in this case bc you are substantiating it while doing the split?
Quote:
String[] str = s.split("-");
*just trying to work out the differences in why it works in one place and not the other- I am leaning towards bc you are substantiating w/ the split yes?
__________________

I code C hash-tag .Net
Reference: W3C W3CWiki .Net Lib
Validate: html CSS
Debug: Chrome FireFox IE
alykins is offline   Reply With Quote
Old 12-29-2011, 04:31 PM   PM User | #6
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,653
Thanks: 4
Thanked 2,451 Times in 2,420 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
String[] is just the datatype, as is int[]. You don't need to specify the size of it until you instantiate it. When an array is returned by something different, it can take the place of the placeholder.
Simple look: T[] -> 4 byte pointer <- T[4] returned
The T[] you declared is simply a pointer to the returned results of the T[4]. The pointer has been assigned, but in Java world I don't know if its a direct memory pointer or if it has multiple levels of indirection. I'd assume multiple levels.

Your thread is different. String.split will return a String[], so you cannot just cast that into an int[] type. Without a defined size of the T[], it is assumed to be that of 0, so you cannot dereference it to write any data into it.
So with your example you could have actually used:
PHP Code:
String[] octets args.getHostAddress().split("\\."); 
The only way to cast it is by iterating it after the fact, which means you'll need to either do something immediately, store it in a collection, or use a pre-defined array size.

Edit:
Sorry, for a better explanation of the problem in your other thread:
int[] i = null; is an int array without a size. Your error came from trying to use i[value], since this would never exist. This is why you needed to use a new int[4] for the size.

Last edited by Fou-Lu; 12-29-2011 at 04:34 PM..
Fou-Lu is offline   Reply With Quote
Old 12-30-2011, 07:05 AM   PM User | #7
albert.chiu
New to the CF scene

 
Join Date: Dec 2011
Posts: 4
Thanks: 1
Thanked 0 Times in 0 Posts
albert.chiu is an unknown quantity at this point
you can have a try...

public static List splitString(String strInput, String strSplitor, boolean trim) {
List listResult = new ArrayList();
if (strInput == null) {
return null;
}
int start = 0;
int end = strInput.length();

while (start < end) {
int delimIdx = strInput.indexOf(strSplitor, start);

if (delimIdx < 0) {
String tok = strInput.substring(start);
if (trim) {
listResult.add(tok.trim());
} else {
listResult.add(tok);
}
start = end;
} else {
String tok = strInput.substring(start, delimIdx);
if (trim) {
listResult.add(tok.trim());
} else {
listResult.add(tok);
}
start = delimIdx + strSplitor.length();
}
}
return listResult;
}
albert.chiu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 03:39 PM.


Advertisement
Log in to turn off these ads.