简体   繁体   中英

how to split this string[LECT-3A,instr01,Instructor 01,teacher,instr1@learnet.com,,,,male,phone,,] as my requirement in java

hello every one i got a string from csv file like this

LECT-3A,instr01,Instructor 01,teacher,instr1@learnet.com,,,,male,phone,,

how to split this string with comma i want the array like this

 s[0]=LECT-3A,s[1]=instr01,s[2]=Instructor 01,s[3]=teacher,s[4]=instr1@learnet.com,s[5]=,s[6]=,s[7]=,s[8]=male,s[9]=phone,s[10]=,s[11]=

can anyone please help me how to split the above string as my array

thank u inadvance

- Use the split() function with , as delimeter to do this.

Eg:

String s = "Hello,this,is,vivek";

String[] arr = s.split(",");

you can use the limit parameter to do this:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Example:

String[]
ls_test = "LECT-3A,instr01,Instructor 01,teacher,instr1@learnet.com,,,,male,phone,,".split(",",12);

int cont = 0;

for (String ls_pieces : ls_test)
    System.out.println("s["+(cont++)+"]"+ls_pieces);

output:

s[0]LECT-3A s[1]instr01 s[2]Instructor 01 s[3]teacher s[4]instr1@learnet.com s[5] s[6] s[7] s[8]male s[9]phone s[10] s[11]

You could try something like so:

String str = "LECT-3A,instr01,Instructor 01,teacher,instr1@learnet.com,,,,male,phone,,";
List<String> words = new ArrayList<String>();
int current = 0;
int previous = 0;
while((current = str.indexOf(",", previous)) != -1)
{           
    words.add(str.substring(previous, current));
    previous = current + 1;
}

String[] w = words.toArray(new String[words.size()]);
for(String section : w)
{
    System.out.println(section);
}

This yields:

LECT-3A

instr01

Instructor 01

teacher

instr1@learnet.com







male

phone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM