Finding a word within a string

Hey everyone,
Just having a little trouble with something.
I'm trying to find a word -- that is, not a substring, an actual word as defined by the english language -- within a string.
For example I don't want "hell" to be found in "hello".. only "hello" to be found.
Currently i've got two strings, one is the sentance (String input), and one is the word to be found in the sentance (String word). I need the program to find the WORD, and then go back and search for the word again and again and again until it reaches the end of the string.
This is what I've got thus far:
          for(i = 0; i < input.length(); i++)
               // This statement checks the string "input" for the string "word" starting at offset 0 (as this is what the variable was first defined as)
               if(input.indexOf(word, offset) >= 0)
                    // If it finds the word at all, this line increases the offset ahead of this word so it doesn't simply find the same word again
                    offset = offset + (input.indexOf(word)) + (word.length());
                    times++;
          }At the moment this searches for the sub-string, not the WORD which is what I would like it to do.
What's the easiest way of going about this? I've been fiddling around trying to add extra sections to the if statement, for example
if((input.indexOf(word, offset) >= 0) && (input.charAt(offset +1) == 32))(32 as in the ASCII character for a space, which would do what I wanted it to do)
But I eventually get errors because at some stage or another the charAt is going to be higher than the actual length of the String. Plus, this only looks if there's a space next to the word - a word can be valid if it has a ! next to it for example, or a comma...
Thanks for any help :)
viddy

I think there's a word boundary marker in regex. So it'd be "\\w+hello\\w+" or whatever the marker is, to be used with a Pattern instance.

Similar Messages

  • To find a word in a string.

    Please, is there a way to find a word in a string?
    For exemple:
    The string contains... "Hello World Java Sun"
    I need to find the word "Java", and I'd like to do not compair char by char... I'd like to do it faster than one by one...
    Is there a way? How should I do? I was thinking to use something like substring... but even it... I need to compair char by char... (or I didn't?)
    Thanks a lot

    go to search engine and learn the String class it will help u in the future.
         indexOf
    public int indexOf(String str)
        Returns the index within this string of the first occurrence of the specified substring. The integer returned is the smallest value k such that:
             this.startsWith(str, k)
        is true.
        Parameters:
            str - any string.
        Returns:
            if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned

  • Finding a pattern within a String

    How can I find a pattern within a string using Java? does Java has the ability to do this or do I have to write a function?

    The String API documentation shows how to do it.

  • Regarding finding of word in a string of Application Server Path

    Hi All,
    I have issue related to finding a certain <b>file name(S)</b> from given <b>Application Server Path</b>.
    Here is the actual issue:
    In my Selection-Screen i have one field by the name of <b>Application Server Path</b> - /pw/data/erp/D5S/pp/down/eppi0720.txt
    Like wise he might enter diffrent file name(s) (or) diffrent pat(s) as per requirement.
    Here my requirement is i need to find file discarding path in to one variable - Remember path might also differ also file name might also differ.
    Is there any <b>Keyword/Command</b> by which we can findout only <b>filename</b> from the <b>path</b>!
    I think with <b>'/'</b> operator we can solve this issue.
    If any body knows solution please post.
    Thanks in advance.
    Thanks & Regards,
    Rayeez.

    Hi,
    use fm EPS_GET_DIRECTORY_LISTING'
    example:
    CALL FUNCTION 'EPS_GET_DIRECTORY_LISTING'
           DESTINATION                   q
           EXPORTING
                dir_name               = folder
                file_mask              = mask
           IMPORTING
                file_counter           = cnt_file
                error_counter          = err_file
           TABLES
                dir_list               = dir_list
    Andreas

  • 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

  • OBIEE - Find position of the last occurrence of a charcter within a string.

    Hi,
    I have a requirement in 11.1.1.6.9 to be locate the position of the last occurrence of a character within a string.
    i.e. Given the following, I would want to locate the last "/":
    This/is/an/exampleI would like to return a value of 11. Now, there could be any number of "/" so I can't always locate the nth one - it must be the last one.
    Anyone any ideas?
    Thanks,
    John

    Your requirement is not complete. just in case you want to extract the last part 'example' just use substring and replace to trim up to required part.
    You may have to go for the same for multiple times.
    ETL is the best to handle this than BI.
    BTW: Check this How to use locate function if multiple occurences of same character
    Edited by: Srini VEERAVALLI on May 10, 2013 10:25 AM
    Good that given link is helped you to solve it ;)
    Edited by: Srini VEERAVALLI on May 13, 2013 7:47 AM

  • How do I find duplicate words in a Numbers spreadsheet?

    Hello, I've created my first document on Numbers and am trying to figure out how to find duplicate words. Ideally, a list of words that repeat in the document and how many times. Is this possible? Thank you in advance for the advice

    It's easy enough to find and count duplicate entries, especially if they are all in a single column, but if you want to count individual words within multi word entries, the problem is more complicated.
    Here's an example for the 'simple' case, using a familiar 155 word passage from English literature.
    The words in the passage are separated into a single line for each word, and stripped of all punctuation. This may be done in Pages, or in Text edit, or in pretty much any word processing software or text editor. Paste the passage into a WP or text document, then use the application's Find/Replace feature to replace all of the spaces with returns. I would also do a second pass replacing all double returns with single returns, then repeat that until Find/Replace reported replacing zero occurrences.
    Punctuation was stripped using Find/Replace
    The prepared list was pasted into column A of a Numbers table.
    Formulas:
    B2: =COUNTIF($A$1:A2,A2)
    C2: =IF(AND(B>1,B=COUNTIF($A,A2)),ROW()-1,999999)
    Fill both down their respective columns to the end of the table.
    The small table is inserted as a Basic table using the Tables button. It contains a Header row, but no Header columns.
    Formula:
    A2: =IFERROR(OFFSET(Table 1 :: $A$1,SMALL(Table 1 :: $C,ROW()-1),COLUMN()-1),"")
    Fill right into B2, then fill both down to the end of the table.
    Descriptions of the functions used, along with their syntax and at least one example of their use in a table are available in the Numbers '09 User Guide, which may be downloaded via the Help menu in Numbers.
    Regards,
    Barry
    PS: Regards to the late Mr. Shakespeare, and thank you for providing the text used.

  • 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.

  • Help me about Searching for a Substring within a String

    Hello everybody,
    I have a problem like this:
    Assume i type a sentence from keyboard: "I want to play football"
    And computer will look for the word "football" to see if this word is in that sentence.
    In this case, computer found it.
    That is it ! Could anybody help me about this ?
    Thank you very much in advance.
    still_learn

    Use the String.indexOf() method:
    String original = "I want to play football";
    int result = original.indexOf("football");
    if (result != -1)
    System.out.println("computer found it");
    If the word "football" is in the original String, the indexOf() method will return the index of the word. If it does not find the word "football", it will return a value of -1. The String API is full of useful methods.
    fitz

  • How to finds specific words in each sentence?

    import java.io.*;
    import java.text.*;
    import java.util.*;
    public class FindingWordsSpecific {
         static String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "every Tuesday"};
      public static void main( String args[] ) throws IOException {
               // the file must be called 'myfile.txt'
               String s = "myfile.txt";
               File f = new File(s);
               if (!f.exists())
                    System.out.println("\'" + s + "\' does not exit. Bye!");
                    return;
               BufferedReader inputFile = new BufferedReader(new FileReader(s));
               String line;
               int nLines = 0;
               while ((line = inputFile.readLine()) != null)
                    nLines++;
                   System.out.println(findTheIndex(line));     
               inputFile.close();
           public static String findTheIndex(String sentence){
                String result = "";
                String[] s = sentence.split("\\s");
              for (String s1: s){
                   for (String s2: days){
                        if (s1.equalsIgnoreCase(s2)) {
                             if(s2.matches("every Tuesday")){
                                             }else if (s2.matches("every Wednesday")){
                                              }What is wrong with it because I tried to find "every Tuesday" in
    myfile.txt: "Go fishing every Tuesday and every Wednesday"
    There is big problem with split statement because it takes each word not more than a word.
    I need to have "every Tuesday" not "Tuesday". How to make it correct codes?

    I am going to give you a picture of how the output will look.
    Here are two sentences from myfile.txt:
    Go fishing every Tuesday and every Wednesday
    Meet with research students on Thursday
    I need to read from myfile.txt and to find specific words in each sentences like this output:
    Every Tuesday : Go fishing
    Every Wednesday : Go fishing
    Thursday : Meet with research students
    Ok. make sense? Now I am trying to figure out how to find specific words in each sentence from myfile.txt.
    That is why I have difficult with the splits statement and loops. Like this:
           public static String findTheIndex(String sentence){
                String result = "";
                String[] s = sentence.split("\\s");
              for (String s1: s){
                   for (String s2: days){
                        if (s1.equalsIgnoreCase(s2)) {
                             if(s2.matches("every Tuesday")){
                             }else if(s2.matches("every Wednesday")){
                             }else if(s2.matches("Thursday")){
                             }else{
                                  System.out.println("That sentence is not working");
                return result;
      }So look at the "Thursday" it is working the output because I have split statement to give me only one word not more than
    a word in sentence. So there is big problem with more than a word in sentence like this "every Tuesday" and it won't work at all because of split. Could you please help me how to do that? I appreciated for that help. Thanks.

  • How do I search for adjacent words within MS WORD?

    I am new to Mac. I need to search WITHIN MS Word Documents for specific phrases. Example: Jim is a good boy. Spotlight will find all documents containing those 5 words, but not those 5 words together. There has to be a way...
    MacBook   Mac OS X (10.4.8)  

    First, thanks, I did. My naive take is that new plug-ins wouldn't be required.
    Second - I don't know about Google finding every document, but it returns some pretty impressive results, and fast (so long as Google indexes the page in the first place of course). You've never used this feature? I do it all the time when I want to see if there's an internet version of a document I have in my hand.
    Here's a random example the feature in action - I went to boingboing.net and snagged a phrase from the October archives: "You should give props to BabyStyle.com for the blue octopus costume". Here's the link to the October page:
    http://boingboing.net/200610_01archive.html
    and here's the link to the successful Google search:
    http://www.google.com/search?num=50&hl=en&lr=&safe=off&c2coff=1&client=firefox-a &rls=org.mozilla%3Aen-US%3Aofficial&q=%22Youshould+give+props+to+BabyStyle.com+for+the+blue+octopuscostume%22&btnG=Search
    Pretty impressive - the internet is a big place!
    Thirdly, there was a program written for OS 9 called "Gopher" that did just that. It was pretty handy. Come to think of it, it may have been written for System 8! It vanished from publication before there was even a web for it to be distributed on, and when I switched to OS X, it wasn't working well under 9. Of course outside of the personal computing realm, there are well known database programs like Lexis and Nexis that perform exact phrase searches on their databases, which are pretty extensive (at least as large as most document collections on most personal computers, I'd venture). In fact if you've never used those programs they have some pretty powerful functions, like searching for any occurrence of a word within so many words of a second target word.
    I'll give you a couple of examples of where phrase searching might come in handy. Suppose I have a collection of e-mails or correspondence (I guess we all do) and I want to find the one in which I facetiously repeated the punchline to the chicken joke - "to get to the other side". (You have to grant I might have a reason for wanting this particular e-mail, okay?) Of course if I search on "get", "other" and "side" I may wind up with four or five hundred results; those are pretty common words. That doesn't help me much. A phrase search,however, will yield, I dunno, three or four documents. Bingo.
    Or, here. I work in an office creating documents all day long. I've been working in this office, on PCs, for 16 years. That's a lot of documents. I may create three dozen or more on a single subject. The documents are all on the same subject and all pretty much have the same words in them. Maybe I've got a single paragraph printed from one of them and want to find the source document. A simple word search will yield back 80% of the lot. A phrase search typed in from the paragraph is almost certainly unique, however, and will give me my document in a blink.
    (Um, I'd have to move all the documents to a Macintosh to do this, but you get the point I hope.)
    Spotlight says it finds "anything anywhere" on your computer. I would use a feature like this *all the time*. Why shouldn't it be able to do it?

  • How find a word in txt from Java??

    Hi everybody...somebody knows how to find an especific word that is located in file txt from java somebody has the code???
    Thanks in advance

    Here is the code for finding a word in txt file from Java.
    import java.io.*;
    public class FindTextFromFile
        public static String getString(String fileName)
            StringBuffer fileContent = new StringBuffer(); //appending long String objects repeatedly is very costly
            try
                BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
                String line = "";
                while((line = fileReader.readLine())!=null)
                    fileContent.append(line);
                    fileContent.append(System.getProperty("line.separator")); //size of line.separator=2
            catch (IOException e)
                e.printStackTrace();
            return fileContent.toString();
        public static int[] getIndicesOf(String fileName, String findWord)
            String fileContent = getString(fileName);
            int[] indices = new int[(int)(fileName.length()/findWord.length())]; //max possible occurances
            int index=0, from=0, incr=0;
            while ((index=fileContent.indexOf(findWord, from))!=-1)
                indices[incr++]=index;
                from=index+findWord.length();
            indices[incr]=-1; //marking the end of search result storing
            return indices;
        public static void main(String[] args)
            String fileName = "rawTextFile.txt";
            String findWord = "is";
            System.out.println(getString(fileName));
            System.out.println();
            System.out.print("Occurences of '"+findWord+"' found: ");
            int[] indices = getIndicesOf(fileName, findWord);
            for (int i=0; indices!=-1 && i<indices.length; i++)
    System.out.print(indices[i]+" ");

  • How to use Class Pattern to find match word ?

    Hi All:
    Now I want find some words in a article . for example , I want to find a word ---"book" . For this purpose , I use java.util.regex.Pattern to do that . Following is my code
    String tmpStr = ".*?[\\W]+book[\\W]+.*?";                         
    Pattern p = Pattern.compile(tmpStr);
    Matcher m = p.matcher(testStr);                // assume testStr is the article
    while ( (m1.find()) ) {
             System.out.println("find");
    }                    However , this code only help me to find some like " book " , " book! " , " !book " . But I also want to find some like "book " or " book" , since there aren't space before book or no space after book . How can I correct my code to do that ?
    Thanks in advance

      String tmpStr = "\\bbook\\b";

  • 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().

  • Java + Regex (Searching one or more words within quotes)

    Hi Everyone,
    I have the following text:
    The brown "cow" jumped over the "contributor licensing agreement" and went to "Burger King" to order chicken wings.
    The text above may change. This is the input text. In the input text, I want to find and print out all phrases that are inbetween quotes. I tried the following:
    Pattern pattern = Pattern.compile("\"(.*)\"");
    Matcher matcher = pattern.matcher(paragraph);
    while(matcher.find()){
        String theMatch=matcher.group();
        System.err.println("Found: "+theMatch);
    }The regex expression works in my regex coach program (which helps me test regex on input strings). In the Java code, however, the application only finds "cow", not "contributor licensing agreement" or "Burger King." What do I need to do in order to find those other two phrases? I want to use this to parse out and find all words or phrases in a document that are inbetween quotes.
    What am I doing wrong??
    jetcat33

    how about using a "reluctant" quantifier "?"
        Pattern pattern = Pattern.compile("\".*?\""); // note the question mark
        Matcher matcher = pattern.matcher(paragraph);
        while(matcher.find()){
            String theMatch=matcher.group();
            System.err.println("Found: "+theMatch);
        }

Maybe you are looking for

  • Excise invoice getting split for every 2 line items in J1IS

    Dear Experts, While doing J1IS - Excise invoice getting split for every 2 line items. can anybody help me. regards, sri ram

  • I want to opt out of BTFON!

    I had an updated modem for my bt infinty service last weekand I have just notice that I have been "opted in" to BTFON. I dont want BTFON and when I check the status section of the BTFON site I get the message "Customer product is not on allowed produ

  • Request for S300 owner (save me please ^^)

    Hi everybody ! I am looking for someone who could make a backup of the BIOS (with Universal BIOS Backup Toolkit) to try a recovery BIOS procedure.(I've a S300/i3). Indeed, downloadable bios on the website are no t in the correct format for recovery p

  • Problem in reterving graphs

    Hi i have to face the problem in reterving or displaying the graph..in a application..and plz help that in Regedit where i should give the path of the graph... plz help me in this regard thx in advance

  • MS Word add-in problem

    With Acrobat XI professional (not with standard verson), when creating a pdf from the open Word file, it often crashes Word program (I am using MS Office 365). The Acrabt add-in in Word disappears and has to checked to show up on Word tool bar. Every