How to add chars to a String

Hi,
I want to construct a string by adding characters to it.
How can I do this ?

Never mind, yes it will work (except that you have to
initialize the string first, like s = "something";)
before using +=. Sorry.actually, you don't. s += "foo" is really shorthand for s = s + "foo".
since the reference s is equal to null, the value null is converted to the String "null".
therefore, String s = null;
s += "foo";has the same effect as
String s = "null" + "foo";so, strictly speaking, you don't have to initialize s to a non-null value, but if you don't, you're not going to get anything you'd like...
and, StringBuffer is definitely the way to go here; otherwise, each time you concatenate a character to your String, you're creating a new Character object and a new String object.
Larry

Similar Messages

  • How to add image between two string

    how to add a image between two string .
    example :
    String one <IMG> String two

    grid1 = new GridLayout( 2, 3, 5, 5);
    container = getContentPane();
    container.setLayout(grid1);
    The parameters in GridLayout specifies 2 rows, 3 columns, 5pixels of horizontal gap, 5pixels of vertical gap.
    Did what i could to help, now can somebody help me with JDialog? =(

  • 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

  • How to add newline into a string

    I need to define a string which contains a newline,
    what i did is :
    String newline = new String();
    newline = "\n";
    but when i add new line to other string, and print it out,
    seems it is not working....
    Anrybody knows why?
    thanks~

    Please keep in mind that newlines differ between platforms. The "\n" is very well known, however in the Windows world a newline is actually "\r\n". Thankfully you may retrieve this value from the JVM.
    String newline = System.getProperty("line.seperator");Also System.out.println() will automatically append the correct newline at the end.
    Meaning that
    System.out.println("Hello");
    System.out.print("Hello" + newline);are esentially the same.

  • How to add elements into java string array?

    I open a file and want to put the contents in a string array. I tried as below.
    String[] names;
    s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
    while (s.hasNext()) {
                    String item = s.next();
                    item.trim();
                    email = item;
                    names = email;
                }But I know that this is a wrong way of adding elements into my string array names []. How do I do it? Thanks.

    Actually you cannot increase the size of a String array. But you can create a temp array with the lengt = lengthofarray+1 and use arraycopy method to copy all elements to new array, then you can assign the value of string at the end of the temp array
    I would use this one:
    String [] sArray = null;
    s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
    while (s.hasNext()) {
        String item = s.next();
        item.trim();
        email = item;
        sArray = addToStringArray(sArray, email);
    * Method for increasing the size of a String Array with the given string.
    * Given string will be added at the end of the String array.
    * @param sArray String array to be increased. If null, an array will be returned with one element: String s
    * @param s String to be added to the end of the array. If null, sArray will be returned.(No change)
    * @return sArray increased with String s
    public String[] addToStringArray (String[] sArray, String s){
         if (sArray == null){
              if (s!= null){
                   String[] temp = {s};
                   return temp;
              }else{
                   return null;
         }else{
              if (s!= null){
                   String[] temp = new String[sArray.length+1];
                   System.arraycopy(sArray,0,temp,0,sArray.length);
                   temp[temp.length-1] = s;
                   return temp;
              }else{
                   return sArray;
    }Edited by: mimdalli on May 4, 2009 8:22 AM
    Edited by: mimdalli on May 4, 2009 8:26 AM
    Edited by: mimdalli on May 4, 2009 8:27 AM

  • How to convert char array to string

    sirs,
    i have written a method in java which will return a randomly generated string of a fixed length. i am creating one one character and inserting it into char array.
    at last i am converting it to string
    like this
    String newpass= pass.toString();// pass is a char array
    but problem is that the string is having different value what i hav generated.
    if i am doing like this..
    String newpass= new String(pass);// pass is a char array
    here newpass is having correct value but having some error
    error in the sense when i print
    System.out.println(newpass+"some text");
    "some text" is not printing
    can you suggest the better way

    /*this is my method */
    private String generateString(int len){
              char pass[] = new char[10];
              int cnt=0;
              int temp=0;
              Random randomGenerator = new Random();
                   for (int idx = 0; idx < 1000; ++idx)
                        temp = randomGenerator.nextInt(1000)%128;
                   if((temp>=65 && temp<=90)||(temp>=97 && temp<=122)||(temp>=48 && temp<=57))
                             pass[cnt]=(char)temp;
                             cnt++;               
                        if(cnt>=len) break;
                   String newpass= pass.toString();
                   String newpass1= new String(pass);
                   System.out.println("passed pass"+newpass+"as"+newpass1+"sa");
              return newpass;
    here newpass and newpass1 are having separate values
    why ??
    Edited by: Shovan on Jun 4, 2008 2:21 AM

  • How to search char in a string

    hi, i am new to JSP.
    i have a string, for example an address "Frauenstrasse 10", i want to split it into street name "Frauenstrasse" and house number "10". but i don't know the syntax to process String. can anyone help? thanks!

    new StringTokenizer(myString," "); // Tokens just space
    or
    new StringTokenizer(myString); // Tokens white space
    token.hasMoreTokens(); - boolean
    token.nextToken(); - Returns String
    Stick in While loop.

  • How to add char to time diemension

    Hi friends,
    I am working with info cube in BI2004s, Iam trying to assign info object( ex;zyear) to time dimension , but CHAR is not getting assign to that dimension.
    am I doing write?
    Regards.
    hari

    In BW3.5 this is indeed not possible.
    But in NW-BI7 is it also not included?
    We have a special schedule in which the production day starts at 06:00:00 hrs and in which we process huge amounts of metering data.
    Is there a strategy that we can get rid of a separate/extra Time dimension+characteristics and save physical tables accordingly for best performance??
    Can we adapt CalDay??
    best regards,
    robert

  • How to delete the last char in a String?

    i want to delete the last char in a String, but i don't want to convert the String to a StringBuffer or an array, who knows how to do?

    Try it in this way
    String MyString = "ABCDEF";
    MyString = MyString.substring(0,MyString.length()-1);

  • How to add a new char in Update rule

    Hi Gurus:
    I copied update rules from an old cube. This new cube is a copy of old cube - almost.
    One of the char is missing in the new cube when compared to old cube. There is a small update routine for that char which I need to introduce to new cube.
    My problem is, I'm not able to figure out how to add the new char in the update rule & start the mapping process..
    Thanks & Regards

    Dear Bhanu: This is what happened.
    When I copied - it defaulted this char with what present in comm structure. Basically the old cube has a routine for this char...
    And the position of this char in the update rule for chars..got realigned.
    I'm sorry - I should have check it properly.
    Thanks a LOT for your time & input...I will assign the points
    Best Regards

  • How to add attributed string to JTextPane

    Hi all,
    Could you tell me how to add an attributed string into a Textpane.
    Textpane only takes a styledDocument. Is there any way to convert attributed string into a styled document.
    Are there any components , which we can include attributed string , instead of simple string. Becoz i want my text to have variable fonts.

    Hello,
    check this short course about [url http://developer.java.sun.com/developer/onlineTraining/GUI/Swing2/shortcourse.html#JFCStyled]JTextPane and StyledDocument.
    Heres a small example:import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.*;
    public class AttributedStringTest extends JFrame
         public static void main(String[] args)
              new AttributedStringTest();
         private JTextPane textPane = null;
         private StyledDocument doc = null;
         AttributedStringTest()
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              initMenuBar();
              initTextPane();
              setSize(500, 300);
              setLocationRelativeTo(null);
              setVisible(true);
         private void initMenuBar()
              JMenuBar mbar = new JMenuBar();
              JMenu menu = new JMenu("StyleConstants");
              JMenuItem item = new JMenuItem("Color");
              item.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        Color color =
                             JColorChooser.showDialog(
                                  AttributedStringTest.this,
                                  "Color Chooser",
                                  Color.cyan);
                        if (color != null)
                             MutableAttributeSet attr = new SimpleAttributeSet();
                             StyleConstants.setForeground(attr, color);
                             textPane.setCharacterAttributes(attr, false);
              menu.add(item);
              JMenu font = new JMenu("Font");
              font.add(item = new JMenuItem("12"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-12", 12));
              font.add(item = new JMenuItem("24"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-24", 24));
              font.add(item = new JMenuItem("36"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-36", 36));
              font.addSeparator();
              font.add(item = new JMenuItem("Serif"));
              item.setFont(new Font("Serif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Serif", "Serif"));
              font.add(item = new JMenuItem("SansSerif"));
              item.setFont(new Font("SansSerif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-SansSerif", "SansSerif"));
              font.add(item = new JMenuItem("Monospaced"));
              item.setFont(new Font("Monospaced", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Monospaced", "Monospaced"));
              font.addSeparator();
              menu.add(font);
              mbar.add(menu);
              setJMenuBar(mbar);
         private void initTextPane()
              doc = new DefaultStyledDocument();
              textPane = new JTextPane(doc);
              JScrollPane scroll = new JScrollPane(textPane);
              getContentPane().add(scroll);
              final JTextField text = new JTextField();
              text.setToolTipText("Please enter something");
              text.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             doc.insertString(doc.getLength(), text.getText(), textPane.getInputAttributes());
                        } catch (BadLocationException bad)
              getContentPane().add(text, BorderLayout.SOUTH);
    //not formatted version:import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.event.*;
    public class AttributedStringTest extends JFrame
         public static void main(String[] args)
              new AttributedStringTest();
         private JTextPane textPane = null;
         private StyledDocument doc = null;
         AttributedStringTest()
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              initMenuBar();
              initTextPane();
              setSize(500, 300);
              setLocationRelativeTo(null);
              setVisible(true);
         private void initMenuBar()
              JMenuBar mbar = new JMenuBar();
              JMenu menu = new JMenu("StyleConstants");
              JMenuItem item = new JMenuItem("Color");
              item.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        Color color =
                             JColorChooser.showDialog(
                                  AttributedStringTest.this,
                                  "Color Chooser",
                                  Color.cyan);
                        if (color != null)
                             MutableAttributeSet attr = new SimpleAttributeSet();
                             StyleConstants.setForeground(attr, color);
                             textPane.setCharacterAttributes(attr, false);
              menu.add(item);
              JMenu font = new JMenu("Font");
              font.add(item = new JMenuItem("12"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-12", 12));
              font.add(item = new JMenuItem("24"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-24", 24));
              font.add(item = new JMenuItem("36"));
              item.addActionListener(new StyledEditorKit.FontSizeAction("font-size-36", 36));
              font.addSeparator();
              font.add(item = new JMenuItem("Serif"));
              item.setFont(new Font("Serif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Serif", "Serif"));
              font.add(item = new JMenuItem("SansSerif"));
              item.setFont(new Font("SansSerif", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-SansSerif", "SansSerif"));
              font.add(item = new JMenuItem("Monospaced"));
              item.setFont(new Font("Monospaced", Font.PLAIN, 12));
              item.addActionListener(
                   new StyledEditorKit.FontFamilyAction("font-family-Monospaced", "Monospaced"));
              font.addSeparator();
              menu.add(font);
              mbar.add(menu);
              setJMenuBar(mbar);
         private void initTextPane()
              doc = new DefaultStyledDocument();
              textPane = new JTextPane(doc);
              JScrollPane scroll = new JScrollPane(textPane);
              getContentPane().add(scroll);
              final JTextField text = new JTextField();
              text.setToolTipText("Please enter something");
              text.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        try
                             doc.insertString(doc.getLength(), text.getText(), textPane.getInputAttributes());
                        } catch (BadLocationException bad)
              getContentPane().add(text, BorderLayout.SOUTH);
    regards
    Tim

  • How to get a char from a String Class?

    How to get a char from a String Class?

    Use charAt(int index), like this for example:
    String s = "Java";
    char c = s.charAt(2);
    System.out.println(c);

  • How to remove last char in a string by space

    I have to implement backspace application(remove a last char in a string , when we pressed a button).
    for ex: I enter the no
    1234
    instead of 1236
    So when i press a button on the JWindow... it should display
    123
    so that i can enter 6 now.
    I tried to display the string "123 " instead over "1234" but it is not working when the no background is specified. but works fine when a background color is specified.
    The string is displayed as
    Graphics2D g = (Graphics2D)window.getGraphics();
    AttributedString as = new AttributedString(string, map);
    g.drawString(as.getIterator(),x,y);
    In the map, the background is set to NO_BACKGROUND.
    Thanks and regards

    Deja vu. I saw this kind of post before, and I'm sure
    it was today.http://forum.java.sun.com/thread.jspa?threadID=588110&tstart=0
    Here it is.

  • How to invoke the char " in a string?

    Hi!
    I�m trying to invoke the char " in a string and I can�t think of any good way to do that.
    plz help.

    use
    String foo = new String("the string foo has the \"a string\" value");

  • How to take last 5 char from a string

    Hi All
    I have a requirement,
    base on some comp i have to populate another field.
    in this case i have compare last 3 char of a string 
    example if total string say asasdffrx i have to take last three char here it is frx.
    always i have to last 3 char.
    i can use +6(3) but it wont work every time because string lenght is not fix for all vaue.
    thanks

    Hi,
    A.H.P sample is ok but insert additional check for strigs shorter than 3 (to avoid negative offset):
    data : n TYPE I.
    n = STRLEN( zfield ) - 3.
    if n >= 0.
    result = zfield+n(3).
    else.
    result = zfield.
    endif.
    Krzys

Maybe you are looking for

  • EFI Update broke my Retina Macbook Pro performance

    Ever since I applied the last EFI Update that was released with 10.8.2 my retina macbook pro has been working awfully. To begin with xcode, I don't know if it's the version 4.5 or what but switching from one plain file to another takes up to 1 minute

  • How can I remove safari data from shared iCloud account?

    Before iOS 8 and family sharing I was using a single iCloud account shared among several Apple devices in my household.  Now that we are all using our own separate Apple Accounts I want to delete shared data from other devices that were using my iClo

  • Autosizing Height in custom component

    I'm recreating a component that kind of like a text area control. I want it's height to autosize based on it's width which is set by it's parent. For instance, say I include it in a resizable window with 100% width, but I want it's height to adjust b

  • Can I transfer photos from iPad1 to IPad retina?  How? Thanks

    Can I transfer photos from iPad 1 to iPad Retina? How? Thanks.

  • Problems to create calender in iphoto 08

    Hello, i would like to create a calender in iphoto08. But it doesn´t work. I can click it but nothing happens. Books and cards are working. Has anyone an idea? Thank you! Mario