Substring of string seperated by commas

Hi All,
I am trying for a logic that i have some emp ids as a string seperated by commas and i need the substring of emp ids as below.
Can any one help in splitting the string as below.
public static void main(String args[]) {
         String empId = "1,2,3,4,5,6,7,8,9,10";
        int i;
           int count = 9;
           for (i = 0; i <= count; i = i + 3)
             System.out.println("Emp IDs are : " +empId);
              Result is:
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
Emp IDs are : 1,2,3,4,5,6,7,8,9,10
But i want the result like:
Emp IDs are : 1,2,3
Emp IDs are : 4,5,6
Emp IDs are : 7,8,9
Emp IDs are : 10
thanks for your help.

It can be helpfull to split the question into smaller pieces.
How many id's do you have. When you have the complete String use
//put the string in an array
String[] stringToArray = longIdString.split(",");
//How any id's
int numberOfIdInArray = stringToArray.length;'
Now you know the number of id's.
Divide the number by 5 and you know the number of id's in one new line
Then make 2 loops. For 5 times add the original string with a begin and endpoint in a new string.
package test;
public class SplitString {
  public static void main(String[] args) {
  //the initial id's
  int numberOfIds = 5000;
  final int NUMBEROFLINES = 5;
  //Make a long string
  String longIdString = "";
  StringBuilder builder = new StringBuilder();
  for(int i = 1; i <= numberOfIds; i++){
  builder.append(i + ",");
  longIdString = builder.toString();
  System.out.println("Original Array: " + longIdString);
  //put the string in an array
  String[] OriginalArray = longIdString.split(",");
  //How any id's
  int numberOfIdInOriginalArray = OriginalArray.length;
  System.out.println("Number of Id's: " +numberOfIdInOriginalArray);
  //Number of id's in one row
  int numberOfIdInOneRow = numberOfIdInOriginalArray / NUMBEROFLINES;
  System.out.println("Id's in one row: " + numberOfIdInOneRow);
  //Make 5 strings and put them in a new array
  String[] theNewStrings = new String[NUMBEROFLINES]; //Aray where you can store the new Strings
  int startpoint = 0;
  int endpoint = startpoint + (numberOfIdInOneRow);
  for(int i = 0; i < NUMBEROFLINES; i++){
  StringBuilder buildNewString = new StringBuilder();
  for (int j = startpoint; j < endpoint; j++){
  //Remember that the first value in an array is at index 0
  buildNewString.append(OriginalArray[j] + ",");
  theNewStrings[i] = buildNewString.toString();
  //Create a new start and endpoint for the next String
  startpoint = startpoint + numberOfIdInOneRow;
  endpoint = startpoint + (numberOfIdInOneRow);
  //Print the new 5 strings
  for(int i = 0; i < theNewStrings.length; i++){
  System.out.println(theNewStrings[i].toString());
In the "real world" you have to program the rounding of the division.

Similar Messages

  • How to make Multiple parameters to sql query string seperated by ,(comma) ..

    Hi,
    I would like to konw how I can make multiple parameters to sql query string seperated by ,(comma)  ..
    For example, this parameters can be printed like 'abc,dde,ggf,eeg' ,once I use  "join(Parameters!rpCode.Value,",")" with report builder , 
    By the way, when I test this multiple parameters by Query Designer of report builder there was no problem,.(using Define query parameters, I put abc,dde,ggf,eeg)
    however, when I run this report , it won't be executing ,  with (rsErrorExecutingCommand)
    Plz, help me....

    If its sql query then it should like this
    Select t.*
    from table t
    inner join dbo.ParseValues(@Parameters,',')f
    on f.val = t.ID
    ParseValues can be found him
    http://visakhm.blogspot.in/2010/02/parsing-delimited-string.html
    or easier way is
    Select t.*
    from table t
    where ',' + @Parameters + ',' LIKE '%,' + CAST(t.ID AS varchar(10)) + ',%'
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Passing values to a loop from a string sepated by commas

    This string i am passing to a stored procedure.
    The string which contains id seperated by commas like(string a='100,101,102,103')
    This values i have to seperate and pass it to a query
    I have to do the query for all the values(i think by looping )
    select dept from employee where id =100

    Since row by row processing is something to be avoided, because it uses needlessly many resources, we suggested a SQL only solution. You can still encapsulate this in a stored procedure like this:
    SQL> create table my_departments
      2  as
      3  select * from departments where 1 = 2
      4  /
    Tabel is aangemaakt.
    SQL> create procedure insert_into_my_departments (p_list_called_a in varchar2)
      2  as
      3  begin
      4    insert into my_departments
      5    ( department_id
      6    , department_name
      7    , manager_id
      8    , location_id
      9    )
    10    select department_id
    11         , department_name
    12         , manager_id
    13         , location_id
    14      from departments
    15     where department_id in
    16           ( select to_number
    17                    ( substr
    18                      ( s
    19                      , instr(s,',',1,level) + 1
    20                      , instr(s,',',1,level+1) - instr(s,',',1,level) - 1
    21                      )
    22                    )
    23               from (select ',' || p_list_called_a || ',' s from dual)
    24            connect by level <= length(p_list_called_a) - length(replace(p_list_called_a,',')) + 1
    25           )
    26    ;
    27  end insert_into_my_departments;
    28  /
    Procedure is aangemaakt.
    SQL> select * from my_departments
      2  /
    Er zijn geen rijen geselecteerd.
    SQL> exec insert_into_my_departments(p_list_called_a => '100,110,120,130')
    PL/SQL-procedure is geslaagd.
    SQL> select * from my_departments
      2  /
      DEPARTMENT_ID DEPARTMENT_NAME                     MANAGER_ID     LOCATION_ID
                100 Finance                                    108            1700
                110 Accounting                                 205            1700
                120 Treasury                                                  1700
                130 Corporate Tax                                             1700
    4 rijen zijn geselecteerd.Regards,
    Rob.

  • Get the column values in a single row seperated by commas

    Hi
    i have two tables project_baseline and project_resource which have the foreign key project_id from the base table project_details. Now iam trying to retrieve data from these tables using the below query :
    select distinct b.TASK_NAME,r.RESOURCE_NAME,() from project_baseline b inner join project_resource r on R.PROJECT_ID=B.PROJECT_ID group by b.TASK_NAME,r.RESOURCE_NAME
    Below is the output snippet :
    TASK_NAME RESOURCE_NAME
    TEST DESIGN PARAGI M
    TEST DESIGN RAJAN M S
    TEST EXECUTION VIBHU ARMA
    TEST EXECUTION PRATHAB GARG
    TEST EXECUTION NAGABHUSHAN G K
    TEST DATA PREPARATION RAJAN M S
    TEST DATA PREPARATION SHIVA MARAN
    TEST CASE REWORK VISWAN RAM
    TEST CASE REVIEW NAGABHUSHAN G K
    REGRESSION SANGEET
    PROJECT SUPPORT VIBHU ARMA
    PROJECT SUPPORT PRATHAB GARG
    PROJECT SUPPORT PARAGI M
    PROJECT SUPPORT NAGABHUSHAN G K
    PROJECT SUPPORT SANGEET
    PROJECT CLOSURE PRATHAB GARG
    i need to get the resource_names in a single row seperated by comma for a single task like following:
    TASK_NAME RESOURCE_NAME
    PROJECT SUPPORT VIBHU ARMA,PRATHAB GARG,PARAGI M,NAGABHUSHAN G K,SANGEET
    Could anyone please help me to get the query for the above formated output?
    Thanks in advance
    Meera
    Edited by: 928378 on May 22, 2012 5:20 AM

    Hi,
    It can be done using xmlagg function.
    For Example :
    Table Data..
    DEPTNO     ENAME
    20     WARD Tree
    23     Shank
    30     BLAKE
    10     MILLER
    30     MARTIN
    10     CLARK
    20     SCOTT
    30     TURNER
    20     ADAMS
    30     JAMES
    20     FORD
    30     BLAKE
    Query:
    SELECT deptno,
    RTRIM (XMLAGG (XMLELEMENT (e, ename || ',')).EXTRACT ('//text()'),
    ) NAME
    FROM emp
    GROUP BY deptno;
    Output :
    DEPTNO     NAME
    10     MILLER,CLARK
    20     WARD Tree,FORD,ADAMS,SCOTT
    23     Shank
    30     BLAKE,TURNER,BLAKE,JAMES,MARTIN
    Thanks,
    Shankar
    Thanks,
    Shankar.

  • Is there an easy way to convert from a String with a comma, ie. 1,000.00 to

    Is there an easy way to convert from a String with a comma, ie. 1,000.00 to a float or a double?
    thanks,
    dosteov

    Like DrClap said: DecimalFormat. However, make sure you understand the Locale things, as explained at http://java.sun.com/j2se/1.3/docs/api/java/text/DecimalFormat.html (which refers to NumberFormat as well) and use them explicitly. Like
    public class FormatTest
      public static void main(String args[])
        try
          // see NumberFormat.getInstance()
          DecimalFormat fmt = new DecimalFormat();
          Number num = fmt.parse("1,000.01");
          System.out.println(num.doubleValue());
        catch(ParseException pe)
          System.out.println(pe);
    }most likely seems OK on your system, but may print "1.0" (or even fail) on some non-English platforms!
    When performing calculations, also see http://developer.java.sun.com/developer/JDCTechTips/2001/tt0807.html
    a.

  • How to print space as thousand seperator and comma as decimal seperator

    Hi All,
    I have requirement where I need to print the amounts with space as thousand seperator and comma as decimal seperator.
    I have a field wrshb which is of type mhnd-wrshb. currently I am printing this. In the adobe layout I have declared this coloumn as Decimal field.
    Now in the output it is printing as comma as thousand seperator and dot as decimal seperator.
    For example ,currently the value is printing as 32,811.41
    but I want the amount as 32 811,41
    I have declared the variable as char16,  using write statement in the interface I moved the value from currency field to char field.
    Then in debugging i checked the value comes as 32,811.41 and it goes to dump with teh reason-cannot interpret as a number.
    Can anyone help me in fixing this?
    Thanks and Regards,
    Karthik Ganti.

    Hi Adam,
    As per initial requirement, I have set the format such that the amount is printing in below format as required.
    Locale---Italian.
    Space as thousand seperator and comma as decimal seperator.
    for example 1 234,45
    As some of the Currencies will not have decimals, now users would like to print amount without decimals. For example in my case amount  printing in KRW ( Korean currency ) is also similar to the above format which is wrong.
    for example Now amount is printing as 55 000,00. But actually it should be 550 000. Similarly for JPY currency also, as it doesnot haves decimals ( checked in TCURX table ).
    I have written some logic in the interface. below is the logic.
    WRITE:
        wa_mhnd1-wrshb to wa_item-wrshb CURRENCY WA_ITEM-WAERS.
    *READ TABLE lt_tcurx INTO lwa_tcurx WITH KEY currkey = wa_item-waers BINARY SEARCH.
      IF sy-subrc  = 0.
      IF lwa_tcurx-currdec = '0'.
      REPLACE ',' WITH SPACE INTO WA_ITEM-WRSHB.
      REPLACE ',' WITH SPACE INTO WA_ITEM-WRSHB.
      else.
       REPLACE ',' WITH SPACE INTO WA_ITEM-WRSHB.
        REPLACE ALL OCCURRENCES OF '.' in  wa_item-wrshb WITH ','.
    endif.
    ENDIF.
    a. when the write statement gets executed amount will be in ,. ( 1,234.45 )format. Then my logic gets executed correctly. In this company code is CH10 ( EUR ) and KR10.
    b. But sometimes after the write statement gets executed amount will be in ., format ( 1.234.45 ). In this case my logic works, but gives the wrong value. In this case company code is VN10 ( EUR )
    In both the cases currency is EUR.
    Will the decimal format change accordingly based on the company code code currency.Can you please tell me why write statement behaved differently.
    Do I need to change any locale in the adobe form, or any other logic to be written in interface. ?  I am trying it out from long time, but not able to fix it.
    Can  you please help me how to achieve this ?
    Thanks and Regards,
    Karthik Ganti.

  • Fields should be quoted seperated by comma while transferring to text file

    Hi Experts,
    I need to show the file contents within double quotes and seperated by comma using 'GUI_DOWNLOAD'
    For eg. The text file contents that are transferred to presentation server should look like,
    "00210000001400","21000000149","","0000149","0014","10"
    "00210006121500","21000612151","","0612151","1215","10".
    I was coded like
    **CONCATENATE c_quotes lv_matnr14 INTO lv_first.**
            **CONCATENATE lw_final-extwg+0(2) c_quotes INTO lv_last.**
            **CONDENSE lv_first NO-GAPS.**
            **CONDENSE lv_last NO-GAPS.**
            **CONCATENATE lv_first**
                        **lw_final-ean11+3(11)**
                        **lw_final-yyshortdesc**
                        **lw_final-ean11+7(8)**
                        **lw_final-ean11+9(4)**
                        **lv_last**
                   **INTO lw_ps_data**
                   **SEPARATED BY c_comma1.**
            **CONDENSE lw_ps_data NO-GAPS.**
            **APPEND lw_ps_data TO rt_ps_data.**
    Can u please suggest if there is other better way than this.....?

    try ABAP forum for a better response - ABAP Development

  • Find Substring in String in Workflow

    I'm trying to separate the content from GUID with metadata, but I can't find the Find Substring in String function in SharePoint Designer 2013 mentioned on
    MSDN. Can anyone provide guidance? Thanks!

    Its a not a function. It is workflow action under Actions menu in your SPD 2013. 
    You can find that action under the Utility Actions and make sure you have selected All Actions as show in the image above.
    Amit

  • Splitting string separated by commas into words and assigning numerical values

    Project details :
    I have a project where a description field is being looked at and based on the values (multiple words) I have to do a vlookup from another spreadsheet to get the dates from the appropriate date fields.
    I have created a user defined function to extract keywords from a list from a table. It extracts words from the string separated by comma delimiter.
        I am thinking of assigning values something like this: cooler = 1, compressor = 2, frame = 2, change of order = b etc.
        So if there is a “cooler, compressor, frame, change of order” in the cell, then it should read as: b12 (unique values). Based on the values, I can do a vlookup on the dates. I tried sumproduct in conjuction with search function but did not
    work. Tried split function but did not quite work.
    Any help regarding this is greatly appreciated. Thank you, regards
    keywords
    engine, compressor, frame, cooler     =Keywords(Wordlist,A2) is the function I am calling
    frame, cooler
    engine, cooler, change order
    cooler

    Hi,
    You're asking this question in the wrong forum, this is a PowerShell forum.
    The Excel VBA forum is this way:
    http://social.msdn.microsoft.com/Forums/en-us/home?forum=exceldev&filter=alltypes&sort=lastpostdesc
    Side note to whoever voted up the OP - why??
    Don't retire TechNet! -
    (Don't give up yet - 12,950+ strong and growing)

  • Display results seperated by comma's

    Hi
    Just wondering if there was a way to display results from seperate rows in one text box where the results are seperated by comma's?
    =First(Fields!ClientId.Value, "DataSet1")
    The example above will just show one ClientId however I would like to list all of them all like below
    C001,C002,C546,F546,H232
    Am I after Lookup/LookupSet?
    Any help appreciated.
    Cheers
    Cheers Chris

    One method is to create a hidden parameter ,make it allow Multiple values and set its default value to be same as dataset field value. Then you can simply use
    =Join(Parameters!ParameterName.value,",")
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Substring for Strings, what do I use for a int variable???

    Hi!
    substring for Strings...
    String s1 = p.substring(1,2);
    but what do I use for a int variable?
    int i1 = integ."???????"(1,2);
    /Henrik

    why, you use maths of course!!
    or if you're not up to that, try this:
    int x = 931;
    String s = x+"";
    String res = s.substring(1, 2);
    and of course set it back to an int
    with Integer.parseInt(res);

  • How to extract substring from string... how to find the index?

    suppose i have a string like
    "string1 string2 string3 string4 string....stringK...stringN"
    i would like to extract the substring from string4 to stringK-1
    where stringK and string3 are pre defined strings (ie, i know exactly what stringK and string3 is).
    is there a function to extract the substring from string4 to stringK-1
    or is there a function i can use to determine the index of the end of string4 and the start of stringK?
    thks!

    If your substrings are seperated by a space (or by any other character that isn't used in any of the substrings), you could use something like StringTokenizer.
    If you wanna get real fancy, use the split method of String.

  • Problem while splitting a string based on ' comma '

    Hi,
    I'm trying to upload a file in .csv format into an internal table. For this i'm declaring an internal table it_iflat and a work area wa_xflat as shown below.
    DATA:  it_iflat type table of string,
           wa_xflat type string.
    Now, once i have data in it_iflat..i loop at each record and split it at the occurance of a comma. as shown below.
    DATA:  it_irec type table of string with header line.
    loop at it_iflat into wa_xflat.
         clear it_irec.
        refresh it_irec.
        split wa_xflat at ',' into table it_irec.
    This is working fine when the <b>last column</b> of the excel sheet is populated. But when this field is left blank in the excel sheet..the total number of values that i get in it_irec is one less than the actual.
    Is this happening because the last column doesn't have a value and since its after the last comma..its getting neglected?
    Could anyone please let me know how to resolve this.
    Thanks in advance
    Harsha.

    If there is a value in the last column, then the value should appear in the last column of your itab.
    Maybe try it this way instead.
    report zrich_0001.
    data: it_iflat type table of string,
          wa_xflat type string.
    data: begin of it_irec occurs 0,
          fld1(10) type c,
          fld2(10) type c,
          fld3(10) type c,
          end of it_irec.
    clear it_irec.   refresh it_irec.
    loop at it_iflat into wa_xflat.
      clear it_irec.
      split wa_xflat at ',' into it_irec-fld1
                                 it_irec-fld2
                                 it_irec-fld3.
      append it_itrec.
    endloop.
    Regards,
    Rich Heilman
    Message was edited by: Rich Heilman

  • How to get substring from string starting from the end of string

    Hi
    How to cut from string:
    $A=C:\ClusterStorage\Volume1\WXP-plwropc300\Virtual Hard Disks\WXP-PLWROPC300_EE20E00F-315E-4781-A6DE-68497D4189B8.avhdx
    this substring (name of VHD file): WXP-PLWROPC300_EE20E00F-315E-4781-A6DE-68497D4189B8.avhdx
    This script should be universal so the best way to be cut all leters from the end of string $A till get the first mark \
    Thank you for help.
    Tomasz
    Kind Regards Tomasz

    PS > Split-Path 'C:\ClusterStorage\Volume1\WXP-plwropc300\Virtual Hard Disks\WXP-PLWROPC300_EE20E00F-315E-4781
    -A6DE-68497D4189B8.avhdx' -leaf
    WXP-PLWROPC300_EE20E00F-315E-4781-A6DE-68497D4189B8.avhdx
    PS >
    That is what "Split-Path" is for:
    ¯\_(ツ)_/¯

  • How to get substring from string using index?

    hi,
    here i am having string ,
    i want the pullareddy from below line ,
    i know how to get from substring.
    but i want to get the above using "index",
    can any help how to do it?
    String str1="janapana,pullareddy, in malaysia";
    jpullareddy

    get the start index with indexAt("pullareddy")
    get the end index with adding the length of the word to the start
    get the char[] of str1 with toCharArray()
    make a new string with the chars from start to end index.

Maybe you are looking for

  • Response object in JSP Dyn page

    Hi SAP EP Gurus, I want to use response.setStatus() mehtod in jspdynpage but it is not working as expected. I am able to use other methods of response object like response.write(). As per my knowledge if i set response.setStatus(200) is should send e

  • Errors in Support Assistant - 5.5.1.0 Build 1828479

    Running 5.5.1.0 Build 1828479 When I click on the monitor tab to see the proactive support uploads status, all I see are errors.  When you hover the mouse over the status it says: cannot establish connection to vmware hosted services, please check th

  • FF29 fails to load Session Manager, old tabs, any add-ons, Cool Preview, etc after upgrade on XP

    FF29 fails to load Session Manager, old tabs, any add-ons, Cool Preview, etc after forced upgrade on an XP system. Connecting to sites, especially support.mozilla.org requires numerous retries. Clicking Add0on shows none of the previous working ones.

  • SRM to R3 rfq sending

    hi, In my developement the requirement is that when i enter a purchase document number in r3, an rfc enabled function module should be called who using this number will fetch purchasing group and vendor from SRM.Please tell me in which table in SRM a

  • Run .app at specific time

    How do I get an app I have made in Automator to run at a specific time? I want to do something like cron jobs.