Using Strings and tokens . . .

Hello,
I was wondering if anyone could help me out with this problem(s). I'm designing a java program that (when a statement is typed in by a user) (1) tells you if it's a sentence, question, or exclamation, (2) it gives you the total amount of words in the statement, (3) tells you the longest word in the statement, (4)and also outputs the number of words that contain 1-3 characters. So far, i've been able to figure out how to do (1) and (2), but I'm really stuck on (3) and (4). Could someone please take a look at my program and tell me what I'm doing wrong. Thanks, Ana : )
// ProgramTwo.java Author: Ana
// Program Two. Demonstrates the use of strings and tokens.
import java.util.Scanner;
import java.io.*;
import java.util.StringTokenizer;
public class ProgramTwo
// Prints a string and various mutations of it.
public static void main (String[] args)
Scanner scan = new Scanner (System.in);
System.out.print("Enter a statement >");
String myString = scan.nextLine();
String oneWord;
if (myString.endsWith("!"))
System.out.println("Your statement ends with an exclamation.");
else
if (myString.endsWith("."))
System.out.println("Your statement is a sentence.");
else
System.out.println("Your statement is a question.");
StringTokenizer st = new StringTokenizer(myString);
System.out.println("There are " + st.countTokens() +
               " word(s) in your statement.");
st = new StringTokenizer(myString);
while (st.hasMoreTokens())
oneWord = st.nextToken();
if (oneWord.length() <= 3)
System.out.println(oneWord); //supposed to determine the number of words that contain up to three
//characters
String longestWord = "";
while (st.hasMoreTokens())
String w = st.nextToken();
if (w.length() > longestWord.length())
longestWord = w;
System.out.print(longestWord); // It's supposed to determine the longest word in the statement
}

Hey Guys,
I just wanted to thank all of you who responded to my message. With your help, I was able to figure out a bunch of other stuff. ChuckBing, I replaced some parts like you said and it worked like a charm! KPSeal, you brought up a good point, I doubled checked with my instructor and he said it was Ok for me to leave that part as is. Lutha, thanks for your input. I was just wondering, is Python similar to Java? I've never heard of it before, then again I've never heard of Java until a couple of months ago : ) Anyways, thanks again!! Ana : )
By the way, here's how my program came out.
// ProgramTwo.java Author: Ana
// Program Two. Demonstrates the use of strings and tokens.
import java.util.Scanner;
import java.io.*;
import java.util.StringTokenizer;
public class ProgramTwo
// Prints and groups various word types and amounts.
public static void main (String[] args)
Scanner scan = new Scanner (System.in);
System.out.print("Enter a statement >");
String myString = scan.nextLine();
String oneWord;
if (myString.endsWith("!"))
System.out.println("Your statement ends with an exclamation.");
else
if (myString.endsWith("."))
System.out.println("Your statement is a sentence.");
else
System.out.println("Your statement is a question.");
StringTokenizer st = new StringTokenizer(myString);
System.out.println("There are " + st.countTokens() +
               " word(s) in your statement.");
int shortWordCount = 0;
int medWordCount = 0;
int longWordCount = 0;
String longestWord = "";
String shortestWord = "";
while (st.hasMoreTokens())
oneWord = st.nextToken();
if (oneWord.length() <= 3)
shortWordCount++;
if (oneWord.length() >= 4 && (oneWord.length() <= 6))
medWordCount++;
if (oneWord.length() >= 7)
longWordCount++;
if (oneWord.length() > longestWord.length())
longestWord = oneWord;
if (oneWord.length() < shortestWord.length())
shortestWord = oneWord;
System.out.println("The shortest word is " + shortestWord + ".");
System.out.println("The longest word is " + longestWord + ".");
System.out.println("There are " + shortWordCount + " short words.");
System.out.println("There are " + medWordCount + " medium words.");
System.out.println("There are " + longWordCount + " long words.");

Similar Messages

  • JButton: Using Strings and Icons

    I am trying to make a JButton so that when it is ...
    1. enabled, an Icon appears without any text
    2. selected, a String appears without any Icon
    3. disabled, a Icon appears without any text
    My Code is as follows...
    equation[i] = new JButton(mathSigns);
    equation.setDisabledIcon(winImage);
    equation[i].setDisabledSelectedIcon(winImage);
    equation[5].setSelected(true);
         if(equation[5].isSelected() == true)
                        equation[5].setText("TEXT");
    Everything works except that When the button is selected, the Icon and the Text shows up instead of just the text showing up. I want the Icon to dissappear and only the text to show up. How can i do this? Thanks!

    Here is a piece of code that might help. I had to use JToogleButtons because I don't really know what a selected regular JButton is.import javax.swing.*;
    import java.io.IOException;
    import java.net.URL;
    import java.awt.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    * User: weebib
    * Date: 12 janv. 2005
    * Time: 03:06:30
    public class MultiStateButton extends JToggleButton {
         private static ImageIcon ICON_ENABLED = null;
         private static ImageIcon ICON_DISABLED = null;
         static {
              try {
                   ICON_ENABLED = new ImageIcon(new URL("http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/tumble/T1.gif"));
                   ICON_DISABLED = new ImageIcon(new URL("http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/images/tumble/T2.gif"));
              } catch (IOException e) {
                   e.printStackTrace();
         public MultiStateButton() {
              super(ICON_ENABLED);
              setModel(new ToggleButtonModel() {
                   public void setSelected(boolean b) {
                        super.setSelected(b);
                        if (b) {
                             setText("tutu");
                             setIcon(null);
                        } else {
                             setIcon(ICON_ENABLED);
                             setText(null);
              setDisabledIcon(ICON_DISABLED);
         public static void main(String[] args) {
              final JFrame frame = new JFrame(MultiStateButton.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panel = new JPanel(new GridLayout(1, 2));
              final JToggleButton firstButton = new MultiStateButton();
              final JToggleButton secondButton = new MultiStateButton();
              firstButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        secondButton.setEnabled(!secondButton.isEnabled());
              secondButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        firstButton.setEnabled(!firstButton.isEnabled());
              panel.add(firstButton);
              panel.add(secondButton);
              frame.setContentPane(panel);
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }

  • Reverse Strings using rercursion and iteration

    Hi,
    I really need some help, am quite new to java and am struggling.
    I want to design 2 methods, both 2 reverse strings.
    1) uses StringBuffer and iteration
    2) uses Strings and recursion
    I would be greatful for any advice or help.
    Thanx xxxxx Nats xxxxxx

    Oh, you need to do it using both methods.... Sorry, didn't realise it was coursework :)
    Using StringBuffer and iteration
    public StringBuffer reverse(StringBuffer buff) {
        int halfLen = buff.length();
        int len = buff.length();
        for(int i=0; i < halfLen; i++) {
             char c1 = buff.getCharAt(i);
             char c2 = buff.getCharAt((len - i) - 1);
             buff = buff.setCharAt(i, c2);
             buff = buff.setCharAt((len - i) - 1, c1);
        return buff;
    }And for String using recursion
    public String reverse(String str) {
        char[] chars = new char[str.length];
        str.getChars(0, chars, 0, str.length());
        reverseChars(chars, 0, str.length() / 2);
        return new String(chars);  
    private reverseChars(char[] chars, int index, int halfLen) {
        //* end condition
        if(index >= halfLen) return;
        topIndex = (chars.length - 1) - index;
        char tmp = chars[index];
        chars[index] = chars[topIndex];
        chars[topIndex] = tmp;
        reverseChars(chars, ++index, halfLen);
    }I only wrote this code on the fly so things may break but it is a start.

  • VISA and Scan string for tokens

    Hi there,
    I am currently developing a piece of software which needs to take in data from an Arduino board via the serial port and parse the input accordingly.
    I have the 2 pieces of code working perfectly well separately, but I can not seem to figure out why they are not functioning properly together.
    Just now, the input is being retrieved fine and passed into the Scan string for tokens method, but it is not being split on the tokens, it is just outputting the string as a whole.
    The input is in the form of 1:0 2:0 3:1 etc. so I am trying to split it on any spaces found.  If I attach a string to the Scan strings for tokens it works fine, just not when I am attaching the data from the serial port to it.
    Any help would be appreciated.
    Attachments:
    input manipulation.vi ‏16 KB

    Hi,
    In the output which you are getting from the serial port, is there space between 1:0 and 2:0 and 3:1? If there is no space between them, then it wont be able to scan for tokens and will output the whole string. I don't have the hardware here and so don't know what exactly is the output which you are receiving. Try to see in the read buffer indicator whether the tokens are seperated by a space or not.
    I have attached your vi after adding a small part in it. If the problem is with the spacing then this will work fine for 1:0 2:0 3:1.
    Regards,
    Nitzz
    (Give kudos to good Answers , Mark it as a Solution if your problem is Solved) 
    Attachments:
    input manipulation.vi ‏18 KB

  • How to read a C structure with string and int with a java server using sock

    I ve made a C agent returning some information and I want to get them with my java server. I ve settled communication with connected socket but I m only able to read strings.
    I want to know how can I read strings and int with the same stream because they are sent at the same time:
    C pgm sent structure :
    char* chaine1;
    char* chaine2;
    int nb1;
    int nb2;
    I want to read this with my java stream I know readline methode to get the first two string but after two readline how should I do to get the two int values ?
    Any idea would be a good help...
    thanks.
    Nicolas (France)

    Does the server sent the ints in little endian or big endian format?
    The class java.io.DataInputStream (with the method readInt()) can be used to read ints as binary from the stream - see if you can use it.

  • How to Split the string using Substr and instr using loop condition

    Hi every body,
    I have below requirement.
    I need to split the string and append with single quotes('') followed by , (comma) and reassign entire values into another variable. so that i can use it where clause of update statement
    for example I am reciveing value as follows
    ALN varchar2(2000):=(12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434);
    Note: In the above variable i see 8 transactions, where as in real scenario i donot how many transaction i may recive.
    after modification i need above transactions should in below format
    ALTR Varchar2(2000):=('12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434');
    kindly help how to use substr and instr in normal loop or for loop or while loop while modifying the above transactions.
    Please help me to sort out this issue.
    Many Thanks.
    Edited by: user627525 on Dec 15, 2011 11:49 AM

    Try this - may not be the best way but...:
    create or replace type myTableType as table of varchar2(255)
    declare
    v_array mytabletype;
    v_new_str varchar2(4000);
    function str2tbl
             (p_str   in varchar2,
              p_delim in varchar2 default '.')
             return      myTableType
        as
            l_str        long default p_str || p_delim;
             l_n        number;
             l_data     myTableType := myTabletype();
        begin
            loop
                l_n := instr( l_str, p_delim );
                exit when (nvl(l_n,0) = 0);
                l_data.extend;
                l_data( l_data.count ) := ltrim(rtrim(substr(l_str,1,l_n-1)));
                l_str := substr( l_str, l_n+length(p_delim) );
            end loop;
            return l_data;
       end;
    begin
      v_array := str2tbl ('12ERE-3MT-4Y,4IT-5O-SD,OP-K5-456,P04-SFS9-098,90P-SSF-334,3434-KJ4-O28,AS3-SFS0-J33,989-3KL-3434', ',');
          FOR i IN 1 .. v_array.COUNT LOOP
             v_new_str := v_new_str || ''''||v_array(i)||'''' || ',';
          END LOOP;
       dbms_output.put_line(RTRIM(v_new_str, ','));
    end;  
    OUTPUT:
    =======
    '12ERE-3MT-4Y','4IT-5O-SD','OP-K5-456','P04-SFS9-098','90P-SSF-334','3434-KJ4-O28','AS3-SFS0-J33','989-3KL-3434'HTH
    Edited by: user130038 on Dec 15, 2011 12:11 PM

  • [svn] 3037: Update flex-config. xml files used by the team and qa webapps to use the {targetPlayerMajorVersion} token instead of a hardcoded player version in the library-path and external-library-path .

    Revision: 3037
    Author: [email protected]
    Date: 2008-08-29 06:54:15 -0700 (Fri, 29 Aug 2008)
    Log Message:
    Update flex-config.xml files used by the team and qa webapps to use the {targetPlayerMajorVersion} token instead of a hardcoded player version in the library-path and external-library-path. This will allow the correct playerglobal.swc to be located when the target player version is set in the flex-config.xml or passed to mxmlc or compc.
    Modified Paths:
    blazeds/trunk/apps/team/WEB-INF/flex/flex-config.xml
    blazeds/trunk/qa/resources/config/flex-config.xml

    Unfortunately I don't have the
    "org.eclipse.swt.win32.win32.x86_3.1.2.jar" file. On my computer
    the folder is not set up the same way (C:\Program Files\Adobe\Flex
    Builder 2\plugins) instead it is set up as (C:\Program
    Files\Adobe\Flex Builder 2\metadata\plugins) but I've looked in
    everything and that file just isn't in there. I've re downloaded it
    twice. Still not there. Is there anything else i can do.

  • Using DataServices and Assemblers with Strings

    I have a Java Assembler which obtains a list of strings, on
    Flex it throws a run-time error saying that i am not using the
    IManaged interface.
    When you use custom AS classes you use the [Managed] metadata
    and that solves it but like i said, i am not using custom objects i
    am using Strings.
    So is it possible to make this work? what do i need to do? i
    wouldn't like to have to create a custom object with a String
    property to make this work, so if anyone has any ideas please let
    me know

    Nope i haven't posted it there yet but i will, still i was
    hoping someone here could help me out, there are many topics
    related to FDS in this forum.

  • Comparing two columns in two tables using partial text strings and copying data between tables

    I have two tables:
    The Vendor table is supplied by a clothing manufacturer and lists product data by row with a column that contains a unique manufacturer ID, such as T5C4.  In this table is a short product description and a long product description that I need to find and copy into the second table, Inventory.
    The Inventory table is an export from our Magento store.  Each row contains a unique inventory number in a column that includes but does not match the unique manufacturer ID from the Vendor table.  For example, the unique inventory number could be T5C4-W12, or RED-T5C4W12 or some other variation.
    For each product in Inventory, I need to find the matching product in Vendor, and then copy the short description and long description from Vendor to Inventory.
    Any tips?  Thanks!
    Karl

    Karl,
    Here's a start, as you requested.
    The formula for Our Inventory Row is:
    =IFERROR(MATCH("*"&A&"*", Our Inventory :: A, 0), "n/a")
    The formula for Brief Description in the inventory table is:
    =IFERROR(INDEX(ABC Products :: $A$1:$C$9,MATCH(ROW(), ABC Products :: $D, 0), 2), "n/a")
    The formula for the Full description in the inventory table is:
    =IFERROR(INDEX(ABC Products :: $A$1:$C$9,MATCH(ROW(), ABC Products :: $D, 0), 3), "n/a")
    The Manufacturer's table knows the concise product numbers, so it has the ability to search the Inventory table for it's product id's using wildcards and it then displays the line number of the item in the inventory table. The Inventory table can then search the manufacturer's table for its row number and can reference the brief and full descriptions.
    This approach has a serious limitation. It will only find the first occurrence in the inventory. Now, if you want to accept this, you can sort all the found descriptions and pull them out of the inventory table, and then the next product in line will display it's description too.
    I wish I could do better with this, but it's all I can come up with at this point, knowing only what you have told me.
    Jerry

  • How to retrieve IndividualStrings from a txt file using String Tokenizer.

    hello can any one help me to retrieve the individual strings from a txt file using string tokenizer or some thing like that.
    the data in my txt file looks like this way.
    Data1;
    abc; cder; efu; frg;
    abc1; cder2; efu3; frg4;
    Data2
    sdfabc; sdfcder; hvhefu; fgfrg;
    uhfhabc; gffjcder; yugefu; hhfufrg;
    Data3
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    val1; val2; val3; val4; val5; val6;
    i need to read the data as an individual strings and i need to pass those values to diffarent labels,the dat in Data3 i have to read those values and add to an table datamodel as 6 columns and rows depends on the data.
    i try to retrieve data using buffered reader and inputstream reader,but only the way i am retrieving data as an big string of entire line ,i tried with stringtokenizer but some how i was failed to retrive the data in a way i want,any help would be appreciated.
    Regards,

    Hmmm... looks like the file format isn't even very consistent... why the semicolon after Data1 but not after Data2 or Data3??
    Your algorithm is reading character-by-character, and most of the time it's easier to let a StringTokenizer or StreamTokenizer do the work of lexical analysis and let you focus on the parsing.
    I am also going to assume your format is very rigid. E.g. section Data1 will ALWAYS come before section Data2, which will come before section Data3, etc... and you might even make the assumption there can never be a Data4, 5, 6, etc... (this is why its nice to have some exact specification, like a grammar, so you know exactly what is and is not allowed.) I will also assume that the section names will always be the same, namely "DataX" where X is a decimal digit.
    I tend to like to use StreamTokenizer for this sort of thing, but the additional power and flexibility it gives comes at the price of a steeper learning curve (and it's a little buggy too). So I will ignore this class and focus on StringTokenizer.
    I would suggest something like this general framework:
    //make a BufferedReader up here...
    do
      String line = myBufferedReader.readLine();
      if (line!=null && line.trim().length()>0)
        line = line.trim();
        //do some processing on the line
    while (line!=null);So what processing to do inside the if statement?
    Well, you can recognize the DataX lines easily enough - just do something like a line.startsWith("Data") and check that the last char is a digit... you can even ignore the digit if you know the sections come in a certain order (simplifying assumptions can simplify the code).
    Once you figure out which section you're in, you can parse the succeeding lines appropriately. You might instantiate a StringTokenizer, i.e. StringTokenizer strtok = new StringTokenizer(line, ";, "); and then read out the tokens into some Collection, based on the section #. E.g.
    strtok = new StringTokenizer(line, ";, ");
    if (sectionNo==0)
      //read the tokens into the Labels1 collection
    else if (sectionNo==1)
      //read the tokens into the Labels2 collection
    else //sectionNo must be 2
      //create a new line in your table model and populate it with the token values...
    }I don't think the delimiters are necessary if you are using end-of-line's as delimiters (which is implicit in the fact that you are reading the text out line-by-line). So the original file format you listed looks fine (except you might want to get rid of that rogue semicolon).
    Good luck.

  • Is Scan String for Tokens documented correctly?

    I attempted to parse the following string using " as the only delimiter (no operators):
    this "is a test" for "you and me"
    The first call produced: "this " w/o the quotes.
    I expected "is a test" w/o the quotes.
    The documentation says the function will return tokens "surrounded by" delimiters. If this is not a bug, I think the documentation should be improved.
    W. Brown

    Thank you for commenting on the Scan String for Tokens documentation. We will look into this issue and try to make the documentation more clear about how this function works.
    We're constantly striving to improve the documentation, so any specific suggestions you have are welcome. In the future, please send any comments on National Instruments documentation to [email protected] so we can address your concerns in a timely matter.
    Kelly Holmes
    LabVIEW Documentation Team
    Kelly H
    LabVIEW Documentation
    National Instruments

  • Scan string for tokens

    Can anyone help me out on how to detect a new line using the scan string for tokens function? I am using the "\n" delimiter but it is not working
     

    Syntyche wrote:
    I opened a text file and display it on string indicator. The following is an example of my text file
    START
    SETMASS 5
    WAIT 5s
    SETVELOCITY 10
    WAIT 3s
    END
    So what I want to do is to obtain the string line by line.
    I am thinking I can use scan string for tokens with delimeter \n.
    So if i put this in while loop, in the first iteration, I would want the ouput to be START
    Second iteration: SETMASS 5
    Third iteration WAIT 5s. and etc....
    In C programming i believe this can be done by using strtok. So i want to have a similar function.
    See James' post above, which is what I was hinting at when I said it could be less complicated.  And that's why I asked WHAT you were trying to do, instead of HOW.  In this latest post, you show WHAT you wanted to do, and doing that in the first place would have made the thread a lot shorter. 

  • "Scan String For Tokens" weird behaviour

    I am trying to carry out the simple task of getting a string with
    comma delimiters and produce a string_array with the values in between
    the commas; this would simplify calling the different parts of the
    string.
    Example:
    INPUT: this,is,an,example
    OUTPUT: this|is|an|example (this would be an array of strings)
    Using a while loop with the two VI "Scan String For Tokens" and
    "Insert to array" should be enough to carry this task. I started
    using a FOR loop as the number of tokens I´ll be using is fixed.
    However I wanted to make the subVI more general by allowing any
    #tokens in the input string and using the token index with a WHILE
    loop to do this. The "token index" output from the "Scan String For
    Tokens" is said to be use
    d in a while loop to process the whole
    string.
    However,I´m getting -1 as an output even if I´ve got more tokens left
    and the while loop therefore exits.
    What am I doing wrong?
    Should I use -2 as the comparison to decide whether I´m at hte end or
    not of the string?
    Cheers and TIA

    Check the offset for -1, not the token index. (See attached image). If course if this is a multiline string, the you also need /n etc as delimiter.
    If the string ends in a delimiter, you need to clip the last array element. I usually use "reshape array" with the output from [n] as input.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    ScanForTokens.gif ‏17 KB

  • Applescript app to batch files using ffmpeg and command

    i'm not a technical person and i hoping that i can get a help to create a custom applescript app. i'd like to create an applescript app to run video files from any folder to encode (using ffmpeg) and save the re-encoded version in a new folder inside the current file folder. i found the script that i need to run inside the applescript:
    ffmpeg -i ORG-FILENAME -c:v libx264 -crf 27 -c:a libfaac -q:a 100 -map_metadata 0 NEW-FOLDER/ORG-FILENAME && touch -r ORG-FILENAME NEW-FOLDER/ORG-FILENAME
    i searched through the forum and found something that might work but my limited knowledge can't get this to work:
    on run
        tell application "Finder"
            set theFolder to (choose folder)
        end tell
        proceed(theFolder)
    end run
    on open theFolder
        proceed(theFolder as alias)
    end open
    on proceed(theFolder)
        tell application "Finder"
            set parentFolder to parent of theFolder as string
            if not (exists parentFolder & "A") then
                make new folder at parent of theFolder with properties {name:"A"}
            end if
        end tell
        tell application "Terminal"
            do script "for f in " & quoted form of POSIX path of theFolder & " do ffmpeg -i \"$f\" -c:v libx264 -crf 27 -c:a libfaac -q:a 100 -map_metadata 0 " & quoted form of (POSIX path of (parentFolder & "A")) & " \"$f\"
    done"
        end tell
    end proceed
    when i run this i get:
    for f in '/Users/admin/Pictures/0/1/' do ffmpeg -i "$f" -c:v libx264 -crf 27 -c:a libfaac -q:a 100 -map_metadata 0 '/Users/admin/Pictures/0/A' "$f"
    done
    macbookpro-7:~ admin$ for f in '/Users/admin/Pictures/0/1/' do ffmpeg -i "$f" -c:v libx264 -crf 27 -c:a libfaac -q:a 100 -map_metadata 0 '/Users/admin/Pictures/0/A' "$f"
    > done
    -bash: syntax error near unexpected token `done'
    can anyone help me please

    You are missing a ";"  after your path argument.
    for f in '/Users/admin/Pictures/0/1/'; do

  • Improving Performen when using String

    Hi all,
    Well, I am developing an application and I use Strings a lot... using the Profile I could see the String class are more than 50% of all memory usage on it. I will try to explain how I am using the String and I hope someone can reply me some tips on how to improve this usage.
    Basically I have Message Exchanger application, this application receives some text messages and forward them (or reply them) by replacing some special string by another ones.
    For example:
    The application receive a message like "This is a sample message ${parameter}."
    And forward "This is a sample message Hello."
    Of course, it is more complicated than that, and has more parameters than just a simple one. The example above is just an swatch
    My source code use a lot of
    String msg =  msg.replace(regex1, text1);
              msg = msg.replace(regex2, text2);The JVM creates a new String for each return of msg replace and I believe this is the main place where I can improve the memory usage. The GC is collecting all resources properly, the problem is that I have hundred of messages like that running what cause thousand of String being created and the GC takes some time to release them.
    Well, that is all. Thanks and Regards

    When doing a bunch of variable substitutions it's better to use a regexp Matcher with the output being sent to a String buffer. If all the variable tokens have the same structure you can do the whole job in one pass. Something like:
    Pattern tokenPatterns = Pattern.compile("\\$\\{(\w+)\\}");
    Matcher m = tokenPattern.matcher(inputString);
    StringBuffer outb = new StringBuffer(inputString.length());
    while(m.find()) {
        String insertText = subsMap.get(m.match(1));
        m.appendReplacement(outb, insertText);
    m.appendTail(outb);

Maybe you are looking for