Fastest way to add spaces to a String?

I need to have strings with a fixed width containing variable length text. The following (working) code does this with stupid if() and for() statements:
        StringBuffer levelName = new StringBuffer(record.getLevel().getName());
        if (levelName.length() < LEVEL_WIDTH) {
            int g = LEVEL_WIDTH - levelName.length();
            for (int i = 0; i < g; i++) {
                levelName.append(' ');
        sb.append(levelName); As this code is called a lot of time, i'm looking for a more efficient way to expand strings to a fixed width (by adding spaces). is there a better performing solution?

In this simple padding situation, there's no real advantage to using a StringBuffer over just a char array:
//(1) do this once:
char[] spaces = new char[LEVEL_WIDTH];
char[] buffer = new char[LEVEL_WIDTH];
java.util.Arrays.fill(spaces, ' ');
//(2) Do this whenever you pad:
int len = yourString.length();
if (len < LEVEL_WIDTH) {
    System.arraycopy(yourString, 0, buffer, 0, len);
    System.arraycopy(spaces, 0, buffer, len, LEVEL_WIDTH-len);
    yourString = new String(buffer); //(*)
}Notes:
1. First off, it should be noted that trying to optimize before profiling could be a waste of time: what if the next operation is a database query that takes 100,000 times are long as this?
2. arraycopy is a native op, so it should run faster than a loop. Arrays.fill calls arraycopy, btw.
3. For efficiency, I reuse arrays buffer and spaces.
4. The char array is copied in line (*). It would be nice to avoid that copying: to copy the original string and append padding directly into the strings buffer, but I don't see how that's possible. Using a StringBuffer involves at least as much copying, as far as I can tell (he says, staring at the source code)...

Similar Messages

  • Acrobat v9 JavaScript Alert Box - any way to add space or line break after each array item?

    I have a Document level Javascript used to identify blank required fields and is triggered on document actions, Print and Save. The script identifies the blank required fields, counts them, and outputs to an Alert box indicating the number of required fields blank and lists the fields by tooltip name. The script identifies the required fields by an asterisk at the end of each tool tip.
    My question is there any way to add a space or a line break after the comma for each listed item?
    Here is an image of the output where the listed items are all run together.
    Here is the code:
    function validateFields()
    //a counter for the number of empty fields
    var flg = 0
    // count all the form fields
    var n = this.numFields
    //create an array to contain the names of required fields
    //if they are determined to be empty
    var fArr = new Array();
    //loop through all fields and check for those that are required
    // all fields that have a '*' in their tool tip are required
    for(var i = 0;i<n;i++){
    var fn = this.getNthFieldName(i);
    var f = this.getField(fn);
    //tool tip is the fields\'s 'userName' property;
    var tt = f.userName
    //test for the '*';
    if(tt.indexOf('*')!=-1 && f.value == f.defaultValue){
    //increment the counter of empty fields;
    flg++;
    //add the fields userName (tool tip) to the list of empty field names;
    fArr[fArr.length] = tt;
    //now display a message if there are empty fields
    if(flg>0){
    app.alert('There are '+flg+' fields that require a value\n\n'+ fArr,3)
    else{
    this.print();

    Thank you! The alert box array items now have a line break, image below.  You know you have made my day and possibly several weeks as now I have more understanding about how to apply everything I have been reading in the Acrobat JavaScript guide and of course as soon as you pointed out using a "join", that triggered some old-days of working with Access and SQL queries.
    I will work on the required attribute to see how I might reference it.  I am laughing at myself now - good luck to me in figuring it out as I was very stick-in-the-mud regarding the line break issue.
    Thanks again and here is the result of the updated code:

  • Fastest way to add multiple images, one after the other, in DW5.5

    There has to be a faster way to add multiple images, one after the other, in a web page rather than just dragging each from the Files tab w/in DW 5.5
    I was a little surprized I couldn't select multiple images and just drag a block and have DW just insert an img tag with empty alts and the source path but maybe there is some options I just haven't found?
    I tried using Bridge to generate a quick html slideshow/gallery but it creates skads of divs and such... I just have to update an older site and was looking for an efficient way to add a bunch of images (random names ugh so just copying-pasting one and changing names is still more manual) that lie next to each other, no breaks inbetween....seems an ideal automated situation.
    I'd settle for an external script or app or something because they come in blocks of 25 approx and I have all my actions in PS set up to size appropriately which is nice so I just wondered if there was something good for this low-level production task.
    Thanks

    Thanks. Yes, I started writing a script but I just wondered if there were hidden gems in DW....so many programs do more than they are intended to do nowadays, I had to ask people who use it more!
    Actually, the fastest was to just dupe one line of code, paste x amount and then just use the pick-wip to point and drag. That at least cut the menu out of the equation.
    I thought I remembered doing a batch insert years ago..maybe in GoLive or before Adobe had DW? DW and GoLive are the only GUI html editors I've ever used..but, may it was just something out of an ealier photoshop...they've taken good stuff out and put good stuff in so many times that I can only remember so much!

  • How to add space before a string a variable.

    Hi,
    If i have a string variable  ' 80 '.I want it as '    80 ' ie some space appended before it.
    I used  concatenate '   '    variable into variable..Its not working.How to do it??
    Thanks.

    check below code
    Concatenate ' ' string into string respecting blanks.
    <b>
    ... RESPECTING BLANKS</b>
    Effect
    The addition RESPECTING BLANKS is only allowed during string processing and causes the closing spaces for data objects dobj1 dobj2 ... or rows in the internal table itab to be taken into account. Without the addon, this is only the case with string.
    Note
    With addition RESPECTING BLANKS, statement CONCATENATE can be used in order to assign any character strings EX>text - taking into account the closing empty character - to target str of type string: CLEAR str. CONCATENATE str text INTO str RESPECTING BLANKS.
    Example
    After the first CONCATENATE statement, result contains "When_the_music_is_over", after the second statement it contains "When______the_______music_____is________ over______" . The underscores here represent blank characters.
    TYPES text   TYPE c LENGTH 10.
    DATA  itab   TYPE TABLE OF text.
    DATA  result TYPE string.
    APPEND 'When'  TO itab.
    APPEND 'the'   TO itab.
    APPEND 'music' TO itab.
    APPEND 'is'    TO itab.
    APPEND 'over'  TO itab.
    CONCATENATE LINES OF itab INTO result SEPARATED BY space.
    CONCATENATE LINES OF itab INTO result RESPECTING BLANKS.
    Rewards if useful.........
    Minal

  • Add space in the string

    Hi
    I have a varchar column, the data in the column have no space in between. I want to keep space after every 20 characters while I select data from this column, how can I acheive this.
    thanks
    Royal Thomas

    If so, try this:
    DECLARE @longStrings TABLE (string VARCHAR(MAX))
    INSERT INTO @longStrings (string) VALUES
    ('123456789012345678901234567890123456789012345678901234567890'),('123456789012345678901234567890123456789012345678901234567890123456'),('12345678901234567890123456789012345678901234567890123456789012345678901234567890')
    ;WITH rString AS (
    SELECT 1 as seq, string, LEFT(string,20)+' ' AS part, RIGHT(string,LEN(string)-20) AS remaining
    FROM @longStrings
    UNION ALL
    SELECT r.seq + 1, r.string, r.part+LEFT(remaining,20)+' ', CASE WHEN LEN(remaining) >= 20 THEN RIGHT(remaining,LEN(remaining)-20) ELSE '' END
    FROM rString r
    INNER JOIN @longStrings ls
    ON r.string = ls.string
    WHERE remaining <> ''
    SELECT string, max(part)
    FROM rString
    GROUP BY string

  • Fastest Way To Add Data Through DI

    For Examples there're 5 or more rows in Matrix when i press add button it takes too long time about 10 seconds more. i dont know whether there's faster way. i did matrix row looping from row 1 to Matrix.rowcount to do oDocument_Lines.add .After all data add i do oDocument.add.
    I know that many developers complaint about the DI Performance, but is there any way to enhance DI performance ? Thanks

    Hi Hamdi,
    There is a work around, If you bind the Matrix to a user defined table (It can be a blank table), and then use the oMatrix.LoadFromDatasource and oMatrix.FlushtoDatasource, you can manipulate/collect/call the data using the dbdatasource object.
    This is quite fast, and I have had no problem with it, and also using a Documents object to do a goods receipt.
    To recap, bound dbdatasource (blank if needed) to a usertable, use flushtodatasource and LoadFromDatasource and use dbdatasource.offset method
    I attach some sample Code.
    Populate your Matrix
    oMatrix.FlushToDataSource()
    For i = 0 To Scanindb.Size - 1
                            If Trim(Scanindb.GetValue(4, i)) = "No" Then
                                ' Right we need to add the item
                                OITMOBject.ItemCode = Trim(Scanindb.GetValue(0, i))
                                OITMOBject.Manufacturer = "-1"
                                OITMOBject.ItemsGroupCode = "101"
                                OITMOBject.UserFields.Fields.Item(4).Value = Scanindb.GetValue(3, i)
                                OITMOBject.UserFields.Fields.Item(5).Value = Scanindb.GetValue(2, i)
                                ret = OITMOBject.Add
                                SBO_Application.MessageBox(ret)
                            End If
                        Next i

  • Add space between Pop Menu Magic items?

    Is there a way to add space between the menu items in
    generated by Pop Menu Magic? By this I mean, can you have the
    various menu items (the "tabs" or "buttons") exist with some space
    between them
    (something
    like this but with maybe more space), as opposed to the default
    way the "tabs" are generated (butted up to one another
    like
    this)?
    I have tried editing the p7pm CSS to acheive this in a page
    design I'm roughing out. I get close sometimes but no cigar.....I
    have tried messing with the list items in the HTML code itself, but
    no luck there either.
    Hope I am making enough sense here....
    Thanks,
    Tommy

    Have you asked the question on the PVII newsgroup? You'd
    probably get a
    much faster response over there
    Nadia
    Adobe� Community Expert : Dreamweaver
    http://www.csstemplates.com.au
    - CSS Templates | Free Templates
    http://www.perrelink.com.au
    - Web Dev
    http://www.DreamweaverResources.com
    - Dropdown Menu Templates|Tutorials
    http://www.adobe.com/devnet/dreamweaver/css.html
    "steelkat" <[email protected]> wrote in
    message
    news:e5fapn$kmo$[email protected]..
    > Is there a way to add space between the menu items in
    generated by Pop
    > Menu
    > Magic? By this I mean, can you have the various menu
    items (the "tabs" or
    > "buttons") exist with some space between them <a
    target=_blank
    > class=ftalternatingbarlinklarge
    > href="
    http://css.maxdesign.com.au/listamatic/vertical11.htm">(something
    > like
    > this but with maybe more space)</a>, as opposed to
    the default way the
    > "tabs"
    > are generated (butted up to one another <a
    target=_blank
    > class=ftalternatingbarlinklarge
    > href="
    http://www.projectseven.com/viewer/index.asp?demo=pmm">like
    > this)</a>?
    >
    > I have tried editing the p7pm CSS to acheive this. I get
    close sometimes
    > but
    > no cigar.....I have tried messing with the list items in
    the HTML code
    > itself,
    > but no luck there either.
    >
    > Hope I am making enough sense here....
    >
    > Thanks,
    >
    > Tommy
    >

  • Need a CS2 workaround - Add space for line at top of text box

    I need a way to add space before a line of text (it's a subheading kind of thing) which is the fist line in the text box, since "space before" in paragraph styles doesn't work for this. I'm stuck using CS2 at work, but I made the layout on CS4 at home that uses a workaround involving 0pt rules offset and the Keep in Frame option. This feature is not in CS2 (ugh).
    Any help is appreciated.

    A yucky way of pulling this off without CS3's (and later) "Keep Above Rule in Frame" could be to set the leading extra large. The default Baseline options for text frames is to ignore leading, but you can change it to use the leading. A drawback is that also impacts your regular text ...
    How about an even yuckier trick?
    1. Make the font extra extra large. InDesign ignores super-extra-big leading by default, but it does honor text size. To be precise: the text size that's in the character panel size box (this is important!). If you make the font extra extra large, this is the size that's going to be used.
    2. Now you have large text ... so scale it back down using the Horizontal and Vertical scale in the Advanced Character Formats. If you made the text twice as large, use 50% / 50% to scale it back.
    3. Done.
    I said it would be yuckie.

  • Fastest way to access data between String and char[]

    Hi all,
    I've been programming a small String generator and was curious about the best and fastest way to do so.
    I've done it in two ways and now hope you can tell me if there is a "more java version" or fastest way between those two or if I'm totally wrong as some classe in the API already does that.
    Here are the codes:
    version 1:
            //describe the alphabet
         String alphabet = "abcdefghijklmnopqrstuvwxyz";
         //The "modifiable String"
         StringBuffer stringBuffer = new StringBuffer();
         //Just put the temporary int declaration outside the loop for performance reasons
         int generatedNumber;
         //Just do a "for" loop to get one letter and add it the String
         //Let's say we need a 8 letters word to be generated
         for (int i=0; i < 8; i++)
             generatedNumber = (int)(Math.random() * 26);
             stringBuffer.append(alphabet.charAt(generatedNumber));
         System.out.println(stringBuffer.toString());
         stringBuffer =null;version 2:
            //describe the alphabet
         char[] alphabetArray = {'a', 'b', 'c', 'd', 'e', 'f',
                        'g', 'h', 'i', 'j', 'k', 'l',
                        'm', 'n', 'o', 'p', 'q', 'r',
                        's', 't', 'u', 'v', 'w', 'x',
                        'y', 'z'}
         //The "modifiable String"
         StringBuffer stringBuffer = new StringBuffer();
         //Just put the temporary int declaration outside the loop for performance reasons
         int generatedNumber;
         //Just do a "for" loop to get one letter and add it the String
         //Let's say we need a 8 letters word to be generated
         for (int i=0; i < 8; i++)
             generatedNumber = (int)(Math.random() * 26);
             stringBuffer.append(alphabetArray[generatedNumber]);
         System.out.println(stringBuffer.toString());
         stringBuffer =null;Basically, the question is, what is the safest, fastest and more "to the rules" way to access a char in a sequence?
    Thanks in advance.
    Edited by: airchtit on Jan 22, 2008 6:02 AM

    paul.miner wrote:
    Better, use a char[] instead of a StringBuffer/StringBuilder, since you seem to know the size of the array in advance.
    Although I imagine making "alphabet" a char[] has slightly less overhead than making it a String
    1. It's a lot clearer to write it as a String.
    2. You can just call toCharArray() on the String to get a char[], instead of writing out each char individually.
    3. Or if you're going to be using a plain alphabet, just use (randomNumber + 'a')
    And use Random.nextInt()Hello and thx for the answers,
    I know I shouldn't put constants in my code, it was just a piece of code done in 1 minute to help a colleague.
    Even if it was just a one minute piece of code, I was wondering about the performance problem on large scale calculating, I mean something like a 25 characters word for billions of customers but anyway, once again, the impact should be minimal.
    By the way, I didn't know the Random Class (shame on me, I still don't know the whole API) and, I don't understand why I should be using this one more than the Random.Math which is static and thus take a few less memory and is easier to call.
    Is it because of the repartition factor?
    According to the API, the Random.Math gives (almost) a uniform distribution whether the Random.nextInt() gives a "more random" int.
    I

  • What is the best way to add hard disk space to macbook pro?

    I'm running out of disk space on my macbook pro. What is the best way to add disk space?

    another way of doing it is to replace your hard drive with a larger one.
    if you're technically capable, it takes 10 minutes for the swap and an hour minimum to clone your hard drive or do a data transfer.  all depends on how much data there is to trandfer or to clone.
    good luck.

  • Fastest way to remove html tags except url in href from string using java

    Hi All,
    Please suggest the, fastest way to remove html tags (stripe) except url in href of an anchor tag from string using java.
    Please help me with the best solution as I use parser but it's taking time to remove the html tags from string of file.
    I want the program should give the performance as 1 millisecond for 2kb file.
    Please help me out... Thanks in advance

    Hi,
    how can I replace the anchor tag in a string, by the url in the href of that anchor tag by using jsoup,
    e. g.
    <code>
    suppose input text is :
    test, string using, dsfg, 1:14 PM, < a t a r ge t="_ablank" s t y l e = " color: red" h r e f = " h t t p : / / t e s t u r l . c o m / i n d e x . j s p ? a = 1 2 3 4 " > s u p p o r t < / a >, s c h e d u l a r t a g , < a t a r g e t = " _ vbblank " s t y l e = " c o l o r : g r e e n " h r e f = " h t t p : / / t e s t u r l g r e e n . c o m / i n d e x . j s p ? a = a s d f a s df 4 " > s u pp o r t r e q < / a > a s d f pq r
    then out put text should be :
    test, string using, dsfg, 1:14 PM, http://testurl.com/index.jsp?a=1234, schedular tag, http://testurlgreen.com/index.jsp?a=asdfasdf4 asdf pqr
    </code>
    Please help at the earliest..
    Thanks in advance
    as this text editor is not supporting html anchor tag the example is not displaying correctly
    Edited by: 976815 on Dec 17, 2012 5:17 AM

  • "Easy" way to add a text string Flex default pre-loader?

    Is there an easy way to add text (company name for example) to the top of the default Flex pre-loader?
    Thanks.

    Sure,
    http://www.flexer.info/2008/02/07/very-first-flex-preloader-customization/
    Johnny
    Please rate answers.

  • Right way to add page.

    Hi,
    Say A.tiff contains 6 pages and B.tiff contains 5 pages. I need to 5 pages of B.tiff into A.tiff, so that A.tiff contains 11 pages. Can someone pls show me the fastest way of acheiving this ?
    Currently I am using ImageDecoder to decode A and B to put all the contents of 11 pages into vector, then use ImageEncoder to encode them as new image say C.tiff. This method is very slow. I hope someone can advise.
    Regards,
    Kok.

    When I try this program proposed by JAI, the C.tiff only contains 2 pages in C.tiff, 1 from A.tiff and the other one from B.tiff. Where went wrong ?
    import java.awt.*;
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.io.*;
    import java.util.*;
    import javax.media.jai.*;
    import javax.media.jai.widget.*;
    import com.sun.media.jai.codec.*;
    import com.sun.media.jai.codecimpl.*;
    * Reads all specified files and stores them into a single multi-page TIFF
    * file called "multipage.tif".
    * Usage: java TIFFIOTest file1 [file2 [file3 ...]]
    public class TIFFIOTest {
        public static void main(String[] args) {
            new TIFFIOTest(args);
        public saveasone(String[] fileNames) {
            RenderedImage[] srcs = new RenderedImage[fileNames.length];
            ParameterBlock pb = (new ParameterBlock());
            pb.add(fileNames[0]);
            RenderedImage src0 = JAI.create("fileload", pb);
            ArrayList list = new ArrayList(srcs.length - 1);
            for(int i = 1; i < srcs.length; i++) {
                pb = (new ParameterBlock());
                pb.add(fileNames);
    list.add(JAI.create("fileload", pb));
    TIFFEncodeParam param = new TIFFEncodeParam();
              param.setCompression(TIFFEncodeParam.COMPRESSION_JPEG_TTN2);
    param.setExtraImages(list.iterator());
    pb = (new ParameterBlock());
    pb.addSource(src0);
    pb.add("multipage.tiff").add("tiff").add(param);
    JAI.create("filestore", pb);

  • Fastest way to grant cube permissions per AMO (250 roles, 30 cubes)?

    Hi there,
    can anybody tell me the fastest way to grant cube permissions in a scenario, where for example 250 roles have to be granted for 30 cubes?
    Now, I do it with AMO, iterating throgh the roles, setting cube permissions.
    My method for granting access looks like this:
    public void GrantCubePermission(Role pRole, Database pDatabase, string pCubeName, ReadAccess pReadAccess, WriteAccess pWriteAccess, ReadSourceDataAccess pReadSourceDataAccess, bool pProcess, ReadDefinitionAccess pReadDefinitionAccess)
    try
    if (pRole == null) return;
    Cube cube = pDatabase.Cubes.FindByName(pCubeName);
    if (cube == null) return;
    CubePermission cubePermission = cube.CubePermissions.FindByRole(pRole.ID);
    if (cubePermission == null)
    cubePermission = cube.CubePermissions.Add(pRole.ID);
    cubePermission.Read = pReadAccess;
    cubePermission.Write = pWriteAccess;
    cubePermission.ReadSourceData = pReadSourceDataAccess;
    cubePermission.Process = pProcess;
    cubePermission.ReadDefinition = pReadDefinitionAccess;
    cubePermission.Update(UpdateOptions.AlterDependents, UpdateMode.UpdateOrCreate);
    catch (Exception ex)
    Msg(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    Doing it this way, the operation tooks about 4 seconds per role (the given method is executed 30 times per role, the number of the cubes to be granted for).
    Finally, for 250 roles, the operation tooks about 16 minutes.
    Is there a way to do it faster?

    Did you consider XMLA ?
    <
    Createxmlns="http://schemas.microsoft.com/analysisservices/2003/engine">
        <
    ParentObject>
            <
    DatabaseID>DAtabasename</DatabaseID>
        </
    ParentObject>
        <
    ObjectDefinition>
            <
    Rolexmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:ddl2="http://schemas.microsoft.com/analysisservices/2003/engine/2"xmlns:ddl2_2="http://schemas.microsoft.com/analysisservices/2003/engine/2/2"xmlns:ddl100_100="http://schemas.microsoft.com/analysisservices/2008/engine/100/100"xmlns:ddl200="http://schemas.microsoft.com/analysisservices/2010/engine/200"xmlns:ddl200_200="http://schemas.microsoft.com/analysisservices/2010/engine/200/200"xmlns:ddl300="http://schemas.microsoft.com/analysisservices/2011/engine/300"xmlns:ddl300_300="http://schemas.microsoft.com/analysisservices/2011/engine/300/300"xmlns:ddl400="http://schemas.microsoft.com/analysisservices/2012/engine/400"xmlns:ddl400_400="http://schemas.microsoft.com/analysisservices/2012/engine/400/400">
                <
    ID>Role</ID>
                <
    Name>ReadRole</Name>
                <
    Members>
                    <
    Member>
                        <
    Name>domain\user</Name>
                    </
    Member>
                    <
    Member>
                </
    Members>
            </
    Role>
        </
    ObjectDefinition>
    </
    Create>

  • How to add spaces at the end of record

    Hi Friends,
    i am creating a file which contains more than 100 records.
    In ABAP i have internal table with on field(135) type c.
    some time record have length 120, somtime 130 its vary on each record.
    but i would like to add space at the end of each record till 135 length.
    Can you please help me how to add speace at the end of record.
    regards
    Malik

    So why did you said that in your first posting? My glass sphere is out for cleaning...
    Instead of type c use strings and add spaces until they have the appropriate length.
    loop at outtab assigning <pout>.
      while strlen( <pout>-val ) < 135.
        concatenate <pout>-val `` into <pout>-val.
      endwhile.
    endloop.

Maybe you are looking for