Length of a String

Hi All -
I have a VB.NET app that produces a PS file containing text and graphics.  I need to keep track, in my VB app, of where some text has printed. Specifically, I have a block of text which will need to be parsed into multiple lines to fit into a fixed width column.  So I would like to figure out how much of the text I can print on the current line before going to the next line. So I need to know the printed width of a given chunk of text.
Is there any way for VB to calculate or somehow get (through a call to ??) the 'stringwidth' of a string of text for a given font?
Thanks for your thoughts.  Bob

Bob,
There are probably two ways, at least, to accomplish what you are after within your VB application:
1. I'm not familiar with VB's text setting capabilities, but I think you could determine string or character widths, spaces, and figure out the break positions as long as you have the same font(s) available to VB as you do for the PS job.
VB starting point:
Dim g As System.Drawing.Graphics = Me.CreateGraphics
Dim str As String = "This is the String to get the width of"
Dim StringSize As SizeF = g.MeasureString(str, Me.Font) 
2. You could load nominal character widths (size 1) from the PS font(s) into a database table that you could access from VB and then multiply the nominal character widths times the size you are setting to determine printed character widths, etc. (This is what I am most familiar with. This technique can be expanded to include kerning pairs and it doesn't require that your VB app host has the PS printer or screen fonts installed on it).
- Marvin

Similar Messages

  • How is the length of a string calculated in Java?  and JavaScript?

    Hi all,
    Do any of you know how the length of a string is being calculated in Java and JavaScript? For example, a regular char is just counted as 1 char, but sometimes other chars such as CR, LF, and CR LF are counted as two. I know there are differences in the way Java and JavaScript calculate the length of a string, but I can't find any sort of "rules" on those anywhere online.
    Thanks,
    Yim

    What's Unicode 4 got to do with it? 1 characteris 1
    character is 1 character.
    strings now contain (and Java chars also) is
    UTF-16 code units rather than Unicode characters
    or
    code points. Unicode characters outside the BMPare
    encoded in Java as two or more code units. So it would seem that in some cases, a single
    "character" on the screen, will require two charsto
    represent it.So... you're saying that String.length() doesn't
    account for that? That sux. I don't know. I'm just making infrerences (==WAGs) based on what DrClap said.
    I assume it would return the number of chars in the array, rather than the number of symbols (glyphs?) this translates into. But I might have it bass ackwards.

  • Length of a string in a combobox exceeds the width of the combobox

    How do you fix this:
    The length of a string in a combobox exceeds the width of the combobox and as a result, the comboBox changes its size :-(
    I don't want it to change the size even if the length of the string exceeds the width of the comboBox
    what should i do?

    ok i got it
              Dimension d =combo.getPreferredSize();
    combo.setPreferredSize(new Dimension(50, d.height));
    anyone with better solution?

  • How to find the total length of the string drawed in a rect?

    Hello Everybody,
    I am drawing a string in on one rect using drawInRect method. This drawInRect method gives us a return value as size of the rect. I need length of the string that is did draw in that rect, but didn't find any api to do this.
    Can anyone tell me , how find the length of the string which we did draw in rect?
    Any help regarding this issue , is highly appreciable.
    Thanks,
    Pandit

    Hi Adreas,
    First of all, very thanks for the response.
    Actually , I am looking for other thing. Using drawInRect method I am drawing contentString in self.rect like below.
    //code
    [contentString drawInRect:self.rect withFont:[UIFont fontWithName:@"Verdana" size:14.0] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
    //End
    My contentString is much larger string, so I am not able to draw it in rect(length: 320.0 height: 460.0) completely. My rect is showing only a part of a contentString. So I need to get that part of string which did draw in the rect, so that I can process my contentString to get the remaining string to draw it a next rect.
    The above code statement is returning me the CGSIZE , it is giving the size of the rect but not giving any information of the string which get draw in that rect.Do you have any idea how to do this?
    Any information on this is highly appreciable.
    Thanks,
    Pandit

  • Length of a string without using any built-in functions

    code that returns the length of a string without using any built-in functions.
    thanks
    Sam

    A string is internally represented by a character array.  An array of characters will reside on the stack, not the heap.  Yes, we always learned that String is a reference type, but what goes on in your memory might still surprise you...
    A struct is internally represented by only it's private properties, sequentially on the stack.
    So basically, what I thought is happening by messing with the structlayout: is only tricking our programming a bit into thinking that the top X bytes on the stack represent a chararray, while actually we put them there as a string.
    Wrong. True. And wrong.
    A string is internally represented by, in that order, an array length, a string length, the chars. None of them resides on the stack.
    An array is internally represented by, in that order, an array length and the chars. None of them resides on the stack.
    When you use the FieldOffset attribute to handle the string as a char array, you don't get anything right:
    - the Length returned is the "array length" of the string, which is equal to the string length + 1.
    - the chars returned by the array indexer are shifted by 2 chars (the length of the "string length" field).
    You can use the FieldOffset to make that work, but it needs a little bit more work.
    unsafe static int Test()
    string myString = "This string may contain many string inside this string";
    string testString = "string";
    int countResult = 0;
    fixed (char* myChars = new StringToChar { str = myString }.chr, testChar = new StringToChar { str = testString }.chr)
    // The 2 first chars of the array are actually the string length.
    int myCharsLength = myChars[1] << 16 | myChars[0];
    int testCharLength = testChar[1] << 16 | testChar[0];
    for (int i = 0; i < myCharsLength - testCharLength + 1; i++)
    if (myChars[i + 2] == testChar[2])
    for (int j = 1; j < testCharLength; j++)
    var c = testChar[7];
    if (myChars[i + 2 + j] != testChar[j + 2])
    goto endOfCharAnalyses;
    countResult++;
    endOfCharAnalyses:
    continue;
    return countResult;

  • Length of the string passed to rwcgi60 in Oracle 6i

    Hello,
    I am running the report from the web. The url will be something like
    http://localhost/cgi-bin/rwcgi60.exe?server=repserver+report=.rep+all the input parameters.
    When the length of the string passed from report= execeeds certain limit(indicated by dashes) I am getting the cgi error
    Error: The requested URL was not found, or cannot be served at this time.
    Oracle Reports Server CGI - Unable to communicate with the Reports Server.
    If I remove some of the select criteria then I could execute the report from the web.
    Any body has any soln. for this.
    Thanks in advance,
    Vanishri.

    Vanishri
    The limit is very high and you should not be hitting this problem. There are couple of fixes done in this area. Please apply the latest patch (Patch 10) and try.
    Other solution is you can have a mapped key in cgicmd.dat file and use the key alone in the URL. In the cgicmd.dat file, you have to map say
    key1: REPORT=your_report.rdf USERID=user_name/password@mydb DESFORMAT=html
    SERVER=repserver DESTYPE=cache
    Please refer to the Publishing reports or Reports services manual at http://otn.oracle.com/docs/products/reports/content.html
    Thanks
    The Reports Team

  • PowerShell: Want to get the length of the string in output

    Hi All,
    I am typing this but it is not working. Does anyone know what I could be doing wrong.
    The command I wrote is:
                         GCI -file  | foreach {$_.name} | sort-object length | format-table name, length
    But it is not working. I am expecting a name of the file and length of the string like 8 characters etc. my file is called mystery so it should have 7 as its output of the name, length.
    Thank-you
    SQL 75

    Get-ChildItem supports both  -File and -Directory.
    Help will help:
    https://technet.microsoft.com/library/hh847897(v=wps.630).aspx
    Read the first couple of parameters to see.
       GCI -file  | sort-object length | format-table name, length | ft -auto
    Seems to be a rasher of bad answers to day.  YOu were just extracting the name property then trying to sort on a property that doesn't exist.
    Do the sort first then select the properties.
    it helps to test answers before posting.  I know because I get bit by posting without thinking to often.  I have to remember to think first.
    ¯\_(ツ)_/¯

  • Variable length declaration in string type

    hi all
    can anyone tell me how to declare length for string type of variables

    Hi,
    The length of a string is not static but variable and adjusts itself to the current field content at runtime. Dynamic memory management is used internally. Strings can have any length. The initial value of a string is an empty string with length 0.
    Hope this will make you clear. Please reward if answer satisfy you !!!
    Regards,
    Jignesh

  • How to calculate the length of a string

    Hi everyone,
    A simple question. How to calculate the length of a string?
    Thanks!

    Hi Wuyia Nata,
      As everyone has suggested you search the forum before posting a question, i guess for basic questions u never have to post a question, you will get the answer in your search. Anyways see the code below for string lenght.
    Data:
      w_string type string,
      w_lenght type i.
    w_string = 'vhdskbvsdkbvdsvnsknvs'.
    w_lenght = strlen( w_string ).
    Write:
      w_lenght.
    With luck,
    Pritam.

  • Want to length of the string

    Hi,
    I have one parameter on the selection screen, when i enter some string on that, it should give me the length of the string. can you pls send me the code.
    Ex: if i enter : enter amount : then it should give the o/p is: 12
    Akshitha.

    use FM
    SWA_STRINGLENGTH_GET  
    enter your string in EXPRESSION and use the others if needed use "X" for all three except EXPRESSION
    EXPRESSION                      GFFHG      
    <b>CONDENSE_NO_GAPS                           
    CONDENSE                                   
    WITH_LEADING_BLANKS                        </b>
    also see STRING_LENGTH
        STRING_LENGTH
    Message was edited by:
            Amit Singla

  • Any method to find out length of a string !!

    Hello friends,
                  I used <i><b>describe</b></i> statement to find out the length of a string, but it actually returns the whole length of the string but not actual no. of char's in this.
    any one suggest a solution for this.
    Senthil

    Hi Senthil
    The ABAP function STRLEN returns the length of a string up to the last character that is not a space.
    [COMPUTE] <n> = STRLEN( <c> ).
    STRLEN processes any operand <c> as a character data type, regardless of its real type. There is no type conversion.
    As with mathematical functions, the keyword COMPUTE is optional.
    DATA: INT TYPE I,
    WORD1(20) VALUE '12345'.
          WORD2(20).
          WORD3(20) VALUE ' 4 '.
    INT = STRLEN( WORD1 ). WRITE INT.
    INT = STRLEN( WORD2 ). WRITE / INT.
    INT = STRLEN( WORD3 ). WRITE / INT.
    The results are 5 , 0, and 4 respectively.
    Regs
    vijay

  • Determining length of a string

    Hi,
    I got a string e.g strx = "abcde". Is there any function to determine the length of the string, here e.g. it would be 5?
    I appreciate any help in advance. Thanks.

    Use the length() method of the String object class
    String strx = "abcde";
    int len = strx.length();
    System.out.println(len);
    //Daniel.

  • Calculate length of a string

    Hello.
    I have written a function to calculate the length of a string, it gives the wrong length can you help me fix the codes?
    public int GetStringLength(String z)
    int y = 1;
    int x = 0;
    while (1 > 0)
    try
    char m = z.charAt(y);
    x = x + 1;
    y = y + 1;
    catch (Exception fini)
    return x;
    }

    Hello.
    I have written a function to calculate the length of
    a string, it gives the wrong length can you help me
    fix the codes?
    public int GetStringLength(String z)
    int y = 1;
    int x = 0;
    while (1 > 0)
    try
    char m = z.charAt(y);
    x = x + 1;
    y = y + 1;
    catch (Exception fini)
    return x;
    }Now that's what I call scratching ones belly by wrapping one's arm around one's backside until reaching the belly.

  • Determining the actual length of a string based on pixels?

    How would you determine the actual length of a string based on pixels? Reason for is because a length of a string containing all " l " chars would be a lot smaller then the length of a string containing all "H" chars based on pixel width.
    thanks,
    newbie

    Yes, look at the FontMetrics class which has methods to do just that. To get a relevant FontMetrics object, try "x.getFontMetrics(f)" where x is a Component and f is the Font your string is represented in.

  • Checking the length of a string in sapscript

    Is there a way to check the length of a string in sapscript?
    What I want to do is, if the length of two strings is greater than a certain ammount, truncate the string.
    But I don't know if is possible inside the sapscript

    Never mind, I did it with a perform instead

  • Length of a string (text) in pixels.

    I'm trying to locate a String's center on an exact position, drawing it to a JPanel. But since i don't know the exact length of the string, it's not that easy. Can anybody help me out there?

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class CenteringStrings
        public static void main(String[] args)
            StringDemoPanel demo = new StringDemoPanel();
            DemoActionPanel action = new DemoActionPanel(demo);
            JFrame f = new JFrame("Centering Strings");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(action, "East");
            f.getContentPane().add(demo);
            f.setSize(500,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class StringDemoPanel extends JPanel
        String text;
        Font font;
        final int
            ASCENT   = 0,
            DESCENT  = 1,
            LEADING  = 2,
            BASELINE = 3;
        int index = -1;
        boolean sizeFlag, boundsFlag;
        public StringDemoPanel()
            text = "Centered text";
            font = new Font("lucida sans oblique", Font.PLAIN, 36);
            sizeFlag = false;
            boundsFlag = false;
            setBackground(Color.white);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics(text, frc);
            TextLayout tl = new TextLayout(text, font, frc);
            int w = getWidth();
            int h = getHeight();
            float textWidth = (float)font.getStringBounds(text, frc).getWidth();
            float ascent  = lm.getAscent();
            float descent = lm.getDescent();
            float leading = lm.getLeading();
            float height  = lm.getHeight();
            float x = (w - textWidth)/2;
            float y = (h + height)/2 - descent;
            g2.drawString(text, x, y);
            // marker for string origin (x,y) on baseline
            //g2.setPaint(Color.blue);
            //g2.fill(new Ellipse2D.Double(x - 1, y - 1, 2, 2));
            // physical space of text
            Rectangle2D textSize = tl.getBounds();
            textSize.setFrame(x, y - textSize.getHeight(),
                              textSize.getWidth(), textSize.getHeight());
            // string bounds
            Rectangle2D bounds = font.getStringBounds(text, frc);
            bounds.setFrame(x, y - ascent - leading, bounds.getWidth(), bounds.getHeight());
            switch(index)
                case ASCENT:
                    Rectangle2D r1 = new Rectangle2D.Double(x, y - ascent, textWidth, ascent);
                    g2.setPaint(Color.magenta);
                    g2.draw(r1);
                    break;
                case DESCENT:
                    Rectangle2D r2 = new Rectangle2D.Double(x , y, textWidth, descent);
                    g2.setPaint(Color.orange);
                    g2.draw(r2);
                    break;
                case LEADING:
                    Rectangle2D r3 = new Rectangle2D.Double(x, y - ascent - leading,
                                                            textWidth, leading);
                    g2.setPaint(Color.yellow);
                    g2.draw(r3);
                    break;
                case BASELINE:
                    Line2D line = new Line2D.Double(x, y, x + textWidth, y);
                    g2.setPaint(Color.blue);
                    g2.draw(line);
            if(sizeFlag)
                g2.setPaint(Color.green);
                g2.draw(textSize);
                System.out.println("above size = " + (int)textSize.getY() + "\n" +
                                   "below size = " +
                                   (int)(h - (textSize.getY() + textSize.getHeight())));
            if(boundsFlag)
                g2.setPaint(Color.red);
                g2.draw(bounds);
                System.out.println("above bounds = " + (int)bounds.getY() + "\n" +
                                   "below bounds = " +
                                   (int)(h - (bounds.getY() + bounds.getHeight())));
        public void setIndex(int i)
            index = i;
            repaint();
        public void setSizeFlag(boolean flag)
            sizeFlag = flag;
            repaint();
        public void setBoundsFlag(boolean flag)
            boundsFlag = flag;
            repaint();
    class DemoActionPanel extends JPanel
        StringDemoPanel sdp;
        JRadioButton
            ascentButton, descentButton, leadingButton, baselineButton, clearButton;
        JRadioButton[] buttons;
        JCheckBox
            sizeCheck, boundsCheck;
        JCheckBox[] checks;
        public DemoActionPanel(StringDemoPanel p)
            sdp = p;
            createComponents();
        private void createComponents()
            ascentButton   = new JRadioButton("ascent");
            descentButton  = new JRadioButton("descent");
            leadingButton  = new JRadioButton("leading");
            baselineButton = new JRadioButton("baseline");
            clearButton    = new JRadioButton("clear");
            buttons = new JRadioButton[] {
                ascentButton, descentButton, leadingButton, baselineButton, clearButton
            ButtonGroup group = new ButtonGroup();
            RadioButtonListener buttonListener = new RadioButtonListener();
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weighty = 1.0;
            gbc.insets = new Insets(2,2,2,2);
            gbc.gridwidth = gbc.REMAINDER;
            gbc.anchor = gbc.WEST;
            for(int i = 0; i < buttons.length; i++)
                add(buttons, gbc);
    group.add(buttons[i]);
    buttons[i].addActionListener(buttonListener);
    sizeCheck = new JCheckBox("text size");
    boundsCheck = new JCheckBox("bounds");
    checks = new JCheckBox[] { sizeCheck, boundsCheck };
    CheckBoxListener checkBoxListener = new CheckBoxListener();
    for(int i = 0; i < checks.length; i++)
    add(checks[i], gbc);
    checks[i].addActionListener(checkBoxListener);
    private class RadioButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JRadioButton button = (JRadioButton)e.getSource();
    if(button == clearButton)
    sdp.setIndex(-1);
    return;
    for(int i = 0; i < buttons.length; i++)
    if(button == buttons[i])
    sdp.setIndex(i);
    break;
    private class CheckBoxListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JCheckBox checkBox = (JCheckBox)e.getSource();
    if(checkBox == sizeCheck)
    sdp.setSizeFlag(sizeCheck.isSelected());
    if(checkBox == boundsCheck)
    sdp.setBoundsFlag(boundsCheck.isSelected());

Maybe you are looking for