Determine characters and words in a string

Hi
How do you write code to scan one line of string input and determine
the total number of characters and words on one line?
Please reply soon.
Thanks,
Sincerely,
Egan

How do I use the stringTokenizer class?http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html
java.util
Class StringTokenizer
java.lang.Object
'- java.util.StringTokenizer
All Implemented Interfaces:
Enumeration
public class StringTokenizer
extends Object
implements Enumeration
The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis.
An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnDelims flag having the value true or false:
If the flag is false, delimiter characters serve to separate tokens. A token is a maximal sequence of consecutive characters that are not delimiters.
If the flag is true, delimiter characters are themselves considered to be tokens. A token is thus either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create the StringTokenizer object.
The following is one example of the use of the tokenizer. The code:      StringTokenizer st = new StringTokenizer("this is a test");
     while (st.hasMoreTokens()) {
         System.out.println(st.nextToken());
     } prints the following output:      this
     is
     a
     test StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
The following example illustrates how the String.split method can be used to break up a string into its basic tokens:     String[] result = "this is a test".split("\\s");
     for (int x=0; x<result.length; x++)
         System.out.println(result[x]); prints the following output:      this
     is
     a
     testP.S. You are welcome.

Similar Messages

  • Using Swedish characters and words in messaging?

    The iPhone tries to insert English words when trying to type in Swedish. Can this spell check be turned off?

    The iPhone tries to insert English words when trying to type in Swedish. Can this spell check be turned off?

  • How to read each and every word from a string.

    Hi all,
       I have a string which is having many label numbers. if the string is lv_str, its value is like, 11111111111111##22222222222222##3333333333333.
    I need to move the values alone into internal table. each value should be updated as a single row into one internal table. How to read each and every word of the string and move to an internal table.
    the internal table should be like this.
    11111111111111
    22222222222222
    3333333333333
    Can any one give me a suggestion in this regard.
    POINTS PROMISED.
    Regards,
    Buvana

    Hi,
    If you know the format and length of the data
    Use split at '#' so that you will get the individual values.
    Thean append it to internal table.
    Reward iof helpful.

  • How to Search for a Date in a string having both characters and date

    Hi ,
      I have a requirement to search DATE in the String having Both Characters and DATE . Please kindly let me know as early as possible.
    Regards
    Anil Kumar K

    Try to use SEARCH command with the pattern, making the pattern as fine as it can, like if you have your date in the format 02/23/2007, you can give
    SEARCH STRING FOR ' //'. (assuming the date has at least a single blank before it)
    WRITE:  SY-SUBRC UNDER 'SY-SUBRC',
    SY-FDPOS UNDER 'SY-FDPOS'.
    SY-FDPOS is set to offset of the string from which you can get the date value
    Refer here
    http://help.sap.com/saphelp_47x200/helpdata/en/fc/eb33cc358411d1829f0000e829fbfe/frameset.htm
    It would have been better if there is something like UNIX "regular expression" matching in ABAP

  • I am having a problem where pdf files on the web (i.e., links in a Word doc) open after an extended time and only as gobbldygook ( a file containing a series of characters and letters that make no sense).  This also happens for another Mac user coworker

    Hi There:  I am having a problem where pdf files on the web (i.e., links in a Word doc) open after an extended time and only as gobbldygook ( a file containing a series of characters and letters that make no sense).  This also happens for another Mac user coworker in my office, while the PCs don't have this problem...  Any help/suggestions for a fix would be most appreciated! 

    Just adding more info - MacBookPro running 10.5.8 and using Safari as the browser.  The problem comes and goes - sometimes the linked Word files will open OK, n others its just a strring of crazy characters... 

  • I want to take a series of hex characters in a string control and produce an HDLC string indicator for example if the data string control is 3F27 then the HDLC string indicator is 7E003F2700B57E

    I want to take a series of hex characters in a string control and produce an HDLC string indicator for example if the data string control is 3F27 then the HDLC string indicator is 7E003F2700B57E

    "thanks for your help "
    Does that mean you figured it out already?
    If not, see this thread for some HDLC related code.
    http://forums.ni.com/ni/board/message?board.id=170&message.id=146859&query.id=3388#M146859
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How to get the second and third.... words in a string

    Hi all,
    is there any way to get the words in a string seperate columns in a row.
    "xxx yyyy zzzz aaaa bbbb"
    required answer is
    a b c d e
    xxx yyyy zzzz aaaa bbbb
    a b c d e are the column names
    Thanks

    WITH t as (
      SELECT 'xxx yyyy zzzz aaaa bbbb' as t FROM dual
    -- end of sample data.
    SELECT t,
           regexp_substr(t, '[^ ]+', 1, 1) as a,
           regexp_substr(t, '[^ ]+', 1, 2) as b,
           regexp_substr(t, '[^ ]+', 1, 3) as c,
           regexp_substr(t, '[^ ]+', 1, 4) as d,
           regexp_substr(t, '[^ ]+', 1, 5) as e
      FROM t;
    T                       A                       B                       C                       D                       E                    
    xxx yyyy zzzz aaaa bbbb xxx                     yyyy                    zzzz                    aaaa                    bbbb                   

  • Stripping Strings of all non alphanumeric characters and spaces

    I've been searching the forums and digging through the String class, but can't seem to find an answer.
    What I need to do is turn any string, such as "Sir, please pass the fish."
    into: "sirpleasepassthefish". The easy part is using allLowerCase which gets it down to "sir, please pass the fish.", but now I need to able to remove all space, commas, exclamation points or whatever other junk that could be in a sentence. Is there any thing in the String fucntion that does it that I missed, or do I have to make my own class to do it?
    Thanks!

    Ok, the last part of the code isn't working:
    sentence = "Dad, bob";
    sentence = sentence.toLowerCase();
    int length = sentence.length();
    char test;
    int a =10; //for TESTING
    ArrayList pal = new ArrayList(length);
    for (int x = 0; x<length; x++)
    test = sentence.charAt(x);
    g.drawString("" + test, 30, a); //for TESTING
    a +=20; //for TESTING
    if ((test > 'a') && (test < 'z'))
    pal.add(sentence.substring(x, x+1));
    the IF statement is allowing everything through, and not stripping any spaces or the comma or such, what am I missing?

  • Delete the first word in a string?

    Hi, i have a code in which i can extract the first three words in a string. after it's found the three first words, i would like it to remove the first one, what could i add?
    this is what the code looks like:
    import java.util.regex.*;
    class Test187D {
         public static void main(String[] args) {
              String word1;
              String word2;
              String word3;
              String partDesc = "Hi my name is SandraPandra";
              Pattern pattern = Pattern.compile("^(\\w+)\\s+(\\w+)\\s+(\\w+)");
              Matcher matcher = pattern.matcher(partDesc);
              //Find the first word of the part desc
              if (matcher.find()) {
                   word1 = matcher.group(1);
                   word2 = matcher.group(2);
                   word3 = matcher.group(3);
                   System.out.println (word1 + " " + word2 + " " + word3);
    } Thank you in advance

    Take the length of the first word, plus one for the length of the space, that's how many characters to remove. Take the substring of the original string from the end of the removed part to the end of the whole string. Look up the String methods length(), and substring().

  • Replacing 'word' in a string

    Hi! I want to replace Strings in a String, but if the the substring which has to be replaced is not a word, then i don't want it to be replaced. Eg.: I want to replace Words for other strings, where words are not substring of other Words :)
    Just want to ask if someone has made this before, and can help me out
    cu
    athalay

    But, my original question wasn't this. I
    want to replace words(string) for other strings in
    sentences(string). I hope it's clearer. So for example
    I have a sentence: This is an applepie. And if I want
    to replace apple for pear, then do not replace this
    sentence for pearpie, just remain it, because there's
    no "apple" word in this sentence. I hope it's clearer.
    My main problem is, that handling the First word of
    the sentence. It easy to replace " "+word+" " for what
    I want, but there are separatorchars like , . etc :)Search for the word you want to replace. Once you have found it, you will need to do a series of other checks...
    1) is it at the beginning or end of the sentence? (then you need to look at the character before or after the word depending on location in entire String to see if it is whitespace or separator character)
    2) is it surrounded by whitespace or separator characters on both sides? (get the surrounding characters and compare to a list of acceptable characters to make this a word, ie " ", ",", ";"...
    Only replace words that pass the conditions (beginning of sentence and followed by whitespace or separator, end of sentence and preceeded by whitespace or separator, or middle of sentence and surrounded by whitespace or separators).

  • Search given string array and replace with another string array using Regex

    Hi All,
    I want to search the given string array and replace with another string array using regex in java
    for example,
    String news = "If you wish to search for any of these characters, they must be preceded by the character to be interpreted"
    String fromValue[] = {"you", "search", "for", "any"}
    String toValue[] = {"me", "dont search", "never", "trip"}
    so the string "you" needs to be converted to "me" i.e you --> me. Similarly
    you --> me
    search --> don't search
    for --> never
    any --> trip
    I want a SINGLE Regular Expression with search and replaces and returns a SINGLE String after replacing all.
    I don't like to iterate one by one and applying regex for each from and to value. Instead i want to iterate the array and form a SINGLE Regulare expression and use to replace the contents of the Entire String.
    One Single regular expression which matches the pattern and solve the issue.
    the output should be as:
    If me wish to don't search never trip etc...,
    Please help me to resolve this.
    Thanks In Advance,
    Kathir

    As stated, no, it can't be done. But that doesn't mean you have to make a separate pass over the input for each word you want to replace. You can employ a regex that matches any word, then use the lower-level Matcher methods to replace the word or not depending on what was matched. Here's an example: import java.util.*;
    import java.util.regex.*;
    public class Test
      static final List<String> oldWords =
          Arrays.asList("you", "search", "for", "any");
      static final List<String> newWords =
          Arrays.asList("me", "dont search", "never", "trip");
      public static void main(String[] args) throws Exception
        String str = "If you wish to search for any of these characters, "
            + "they must be preceded by the character to be interpreted";
        System.out.println(doReplace(str));
      public static String doReplace(String str)
        Pattern p = Pattern.compile("\\b\\w+\\b");
        Matcher m = p.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (m.find())
          int pos = oldWords.indexOf(m.group());
          if (pos > -1)
            m.appendReplacement(sb, "");
            sb.append(newWords.get(pos));
        m.appendTail(sb);
        return sb.toString();
    } This is just a demonstration of the technique; a real-world solution would require a more complicated regex, and I would probably use a Map instead of the two Lists (or arrays).

  • Extract words from a string

    select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
    PL/SQL Release 11.1.0.7.0 - Production
    CORE    11.1.0.7.0    Production
    TNS for Linux: Version 11.1.0.7.0 - Production
    NLSRTL Version 11.1.0.7.0 - ProductionI want to extract xyz_xyz,abc_abc words from the string ' select * from TEMP_TABLE where trunc(xyz_xyz) = ''xyz'' and trunc(abc_abc) = ''abc'') '
    i have tried with this query...
    select regexp_substr('select * from TEMP_TABLE where trunc(xyz_xyz) = ''xyz'' and trunc(abc_abc) = ''abc'')', 'trunc[^'''']+''') from dual
    can some one help me on this?
    Thanks,
    Mike

    Hi, Mike,
    Mike wrote:
    I apologize for this..
    create table TEMP_TABLE ( col1 varchar2(10),col2 varchar2(10));
    insert into TEMP_TABLE values('   xyz   ','abc      ');
    insert into TEMP_TABLE values('   xyzxyz ','abcabc    ');
    insert into TEMP_TABLE values('   xyz123 ','abc546  ');
    insert into TEMP_TABLE values('xyz','abc');
    commit
    select * from TEMP_TABLE where trim(col1) ='xyz' and trim(col2) ='abc'
    desired output
    col1,col2
    So the correct output is one row, containing these 9 characters
    col1,col2which do not appear in the table. is that right?
    How is that output related to the data that is in the table? Do you want that output to appear if there are any rows where TRIM (col1) = 'xyz' and TRIM (col2) = 'abc' (for example, either of these two rows from you sample data:
    insert into TEMP_TABLE values('   xyz   ','abc      ');
    insert into TEMP_TABLE values('xyz','abc');), and would you want the result set to contain no rows if the table contained no row like that?
    If so,
    SELECT DISTINCT
         'col1,col2'     AS desired_output
    FROM     temp_table
    WHERE     TRIM (col1)     = 'xyz'
    AND     TRIM (col2)     = 'abc'
    ;I hope this answers your question.
    I have a feeling that it doesn't, or perhaps you have more than one question, since this your earlier messages seemed to have something to do with locating text that was surrounded by single-quotes, and the sample data you posted doesn't contain any single-quotes.

  • Here's how to find the right word in a string

    I needed to find the rightmost word in a string. I didn't find a simple formula in these forums, but I now have one, so I wanted to share it. Hope you find it useful.
    Assuming that the string is in cell A1, the following will return the rightmost word in the string:
    RIGHT(A1,LEN(A1)-FIND("*",SUBSTITUTE(A1," ","*",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))

    I found the problem. Whatever character was being used in the substitution was parsed out by the forum parser. I replaced it with "œ" (option q on my keyboard).
    =RIGHT(A1,LEN(A1)-FIND("œ",SUBSTITUTE(A1," ","œ",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))
    Still needs an error check for a single-word "sentence" and to remove the trailing period but it does seem to work. Pretty slick.
    Message was edited by: Badunit
    I see below that the problem was fixed by the OP.
    Message was edited by: Badunit

  • SharePoint 2010, Visual Studio 2010, Packaging a solution - The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

    Hi,
    I have a solution that used to contain one SharePoint 2010 project. The project is named along the following lines:
    <Company>.<Product>.SharePoint - let's call it Project1 for future reference. It contains a number of features which have been named according
    to their purpose, some are reasonably long and the paths fairly deep. As far as I am concerned we are using sensible namespaces and these reflect our company policy of "doing things properly".
    I first encountered the following error message when packaging the aforementioned SharePoint project into a wsp:
    "The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters."
    I went through a great deal of pain in trying to rename the project, shorten feature names and namespaces etc... until I got it working. I then went about gradually
    renaming everything until eventually I had what I started with, and it all worked. So I was none the wiser...not ideal, but I needed to get on and had tight delivery timelines.
    Recently we wanted to add another SharePoint project so that we could move some of our core functinality out into a separate SharePoint solution - e.g. custom workflow
    error logging. So we created another project in Visual Studio called:
    <Company>.<Product>.SharePoint.<Subsystem> - let's call it Project2 for future reference
    And this is when the error has come back and bitten me! The scenario is now as follows:
    1. project1 packages and deploys successfully with long feature names and deep paths.
    2. project2 does not package and has no features in it at all. The project2 name is 13 characters longer than project1
    I am convinced this is a bug with Visual Studio and/or the Package MSBuild target. Why? Let me explain my findings so far:
    1. By doing the following I can get project2 to package
    In Visual Studio 2010 show all files of project2, delete the obj, bin, pkg, pkgobj folders.
    Clean the solution
    Shut down Visual Studio 2010
    Open Visual Studio 2010
    Rebuild the solution
    Package the project2
    et voila the package is generated!
    This demonstrates that the package error message is in fact inaccurate and that it can create the package, it just needs a little help, since Visual Studio seems to
    no longer be hanging onto something.
    Clearly this is fine for a small time project, but try doing this in an environment where we use Continuous Integration, Unit Testing and automatic deployment of SharePoint
    solutions on a Build Server using automated builds.
    2. I have created another project3 which has a ludicrously long name, this packages fine and also has no features contained within it.
    3. I have looked at the length of the path under the pkg folder for project1 and it is large in comparison to the one that is generated for project2, that is when it
    does successfully package using the method outlined in 1. above. This is strange since project1 packages and project2 does not.
    4. If I attempt to add project2 to my command line build using MSBuild then it fails to package and when I then open up Visual Studio and attempt to package project2
    from the Visual Studio UI then it fails with the path too long error message, until I go through the steps outlined in 1. above to get it to package.
    5. DebugView shows nothing useful during the build and packaging of the project.
    6. The error seems to occur in
    CreateSharePointProjectService target called at line 365 of
    Microsoft.VisualStudio.SharePoint.targetsCurrently I am at a loss to work out why this is happening? My next task is to delete
    project2 completely and recreate it and introduce it into my Visual Studio solution.
    Microsoft, can you confirm whether this is a known issue and whether others have encountered this issue? Is it resolved in a hotfix?
    Anybody else, can you confirm whether you have come up with a solution to this issue? When I mean a solution I mean one that does not mean that I have to rename my namespaces,
    project etc... and is actually workable in a meaningful Visual Studio solution.

    Hi
    Yes, I thought I had fixed this my moving my solution from the usual documents  to
    c:\v2010\projectsOverflow\DetailedProjectTimeline
    This builds ok, but when I come to package I get the lovely error:
    Error 2 The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. C:\VS2010\ProjectsOverflow\DetailedProjectTimeline\VisualDetailedProjectTimelineWebPart\Features\Feature1\Feature1.feature VisualDetailedProjectTimeline
    Now, the error seems to be related to 
    Can anyone suggest what might be causing this. Probably some path in an XML file somewhere. Here is my prime suspect!
    <metaData>
    <type name="VisualDetailedProjectTimelineWebPart.VisualProjectTimelineWebPart.VisualProjectTimeline, $SharePoint.Project.AssemblyFullName$" />
    <importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
    </metaData>
    <data>
    <properties>
    <property name="Title" type="string">VisualProjectTimelineWebPart</property>
    <property name="Description" type="string">My Visual WebPart</property>
    </properties>
    </data>
    </webPart>
    </webParts>
    .... Unless I can solve this I will have to remove the project and recreate but with simple paths. Tho I will be none the wiser if I come across this again.
    Daniel

  • Read Only TextAreas with Carriage Return, Line Breaks and Word Wrapping

    Hi all,
    I know there are a few posts around this subject but I cannot find the answer to the exact problem I have.
    I have a page that has a 'TextArea with Character Counter' (4000 Chars) that is conditionally read only based on the users credentials (using the 'Read Only' attributes of the TextArea item).
    When the field is editable (not Read Only) everything works fine but when I make the field Read Only I start to have problems:
    The first problem is that the Carriage Return and Line Breaks are ignored and the text becomes one continuos block. I have managed to fix this by adding pre and post element text of pre and /pre tags. This has made the Carriage Return and Line Breaks word nicely and dispaly correctly.
    However, it has introduced a second problem. Long lines, with no Carriage Returns or Line Breaks, now extend to the far right of the page with no word wrapping, making my page potentially 4000+ characters wide.
    How can I get the field to be display only, with recognised Carriage Returns and Line Breaks, and Word Wrapping inside a fixed width of, say, 150 characters?
    Many thanks,
    Martin

    Hi,
    Just a cut and paste of yours with the field name changed:
    htp.p('<script>');
    htp.p('$x("P3_COMMENTS").readonly=true;');
    htp.p('</script>');I also have the following in the page HTML Header, could they be conflicting?
    <script type="text/javascript" language="JavaScript">
    function setReleaseToProd(wpTypeCode){
       //setReleaseToProd($v(this))
      var get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=set_release_to_prod',0);
      get.addParam('x01',wpTypeCode);
      gReturn = get.get();
      if(gReturn) {
         $s('P3_RELEASE_TO_PROD',gReturn);
      get = null;
    </script>I am a long way from knowing much about Javascript (this page code was written by someone else) so all help is much appreciated.
    Martin

Maybe you are looking for

  • Error while creating CVC in background in SCM 7.0

    Hi Experts, I'm running creation of CVC in background,but the job is getting cancelled.In job log I can find below error messages. Message Text : Internal Error /SAPAPO/SCMB_PSTRU_PLOB_TEMPL=>RAISE_EXCEPTION_FRO Message class :  /SAPAPO/SCMB_PSTRU Me

  • HT1848 Trying to move files from iPad to new MacBook

    Hi. I'm trying to move my music etc from an iPad to my new Macbook. My previous computer (PC) died some time ago, so I have no backups of the info on my iPad. (Well, a backup from about a year ago!) I lost my iPad data once before, after doing an OS

  • Moving Music from my Ipod to a new computer

    I recently had a hard drive crash. So, I needed to reinstall Itunes and now I have no idea how to get the music from my Nano to my itunes folder. Help?

  • How do I change a mobile account back to a local account?

    I posted this under the "Using OS X Server" but having got any replies, so I thought I'd post it under PHD. Our company split into two seperate companies. We moved and the server stayed. All of our machines were on the server and had portable home di

  • Hydraulic system - how to control a servo valve?

    Thanks for ur attention. I just set up a oil hydraulic system and mechanism that is such a MTS(material test system). And my question is how to let my cylinder go forward at a constant velocity. Because when the cylinder contact my specimen(I have ma