Function to search a Strings within Arrays

Hi all,
trying to make a soccer tournement management system primarily using Java with NetBeans.
Having trouble finding info on a how to function. Would like to search either
- last name
- first name
- by suburb
- player jersey number. (search int, instead of string [just numbers])
all these teams are going to pre-written into Arrays, so are just searching the array.
so i guess thats 4 different functions, but similar. Sorry if this is sounding a little to C instead of Java, still a newbi.
Cheers all

Here's a Collections tutorial.
http://java.sun.com/docs/books/tutorial/collections/
The simplest thing to do would be to methods like: public List getByLastName(String lastName) which would then iterate over each player and add a player to the List that's being returned if his name matches.
The performance won't be great, but if you only have a few dozen or few hundred players, it might be okay, depending on how often it's being called.
For something that's a little cleaner design and probably would perform better, you'd need a more complex data structure than you can probably grasp at this point. (Not trying to be insulting--just pointing out that you seem to be new to this, and that kind of data structure is not an intro-level thing.)
Also, have you thought about how you're going to store the data? Will it be in files, or are you just going to hardcode it all right into the program?

Similar Messages

  • How to search a String within a text file ?

    ************** text file ****************
    Good bye good
    bye good bye
    good bye
    good bye good
    bye good
    ************** Input and Output ****************
    Input: good bye
    Output:
    total strings Matched: 5
    whichlinesmatched: 2
    whichlinesmatched: 2
    whichlinesmatched: 3
    whichlinesmatched: 4
    whichlinesmatched: 5
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    whichlinesmatched: 0
    ** but the desired output is 3, and only line 2, 3, 4 matched
    ** Could you please have further help about this? Thank you.
    ************** the codes****************
    import java.io.*;
    public class Tokenize{
    public static void main( String args[] ){
    int maxNumberOfLine = 1000; //the maximium number of line in data file for input
    String fileName = "test"; // file name for data input
    String stringForCount = "good bye"; // specified word for counting
    int totalStringMatched = 0; // number of word matched
    int[] whichLineMatched; // line number for each word matched
    whichLineMatched = new int[maxNumberOfLine];
    // Input string (stringForCount) has been stored in a string array, wordForCompare[]
    // For example: stringForCount = "good bye"
    int stringLength = 2;
    String wordForCompare [] = { "good" , "bye" };
    // wordForCompare[0] = good
    // wordForCompare[1] = bye
    int wordFromFile;
    StreamTokenizer sttkr;
    try{
    FileInputStream inFile = new FileInputStream(fileName); //specifying the file to be opened
    Reader rdr = new BufferedReader(new InputStreamReader(inFile)); //assigned a StreamTokenizer
    sttkr = new StreamTokenizer(rdr);
    sttkr.eolIsSignificant(false);
    System.out.println("Searching for word : " + stringForCount );
    while( (wordFromFile = sttkr.nextToken()) != StreamTokenizer.TT_EOF)
    System.out.println( "going looping through file, token is: " + sttkr.sval );
    if(sttkr.sval.equals(wordForCompare[0])){
    if (stringLength == 1) {
    totalStringMatched++;
    whichLineMatched[totalStringMatched-1]=sttkr.lineno();
    } else {
    for (int p=1; p < stringLength; p++) {
    wordFromFile = sttkr.nextToken();
    System.out.println( sttkr.sval );
    if (!(sttkr.sval.equals(wordForCompare[p])))
    break;
    else if (p==stringLength-1) {
    totalStringMatched++;
    whichLineMatched[totalStringMatched-1] = sttkr.lineno();
    } // end of else
    } // end of for-loop
    } // end of else
    System.out.println( " total strings Matched: " + totalStringMatched );
    } // end of if
    }//end of while for wordFromFile
    for( int i = 0; i < 10; i++)
    System.out.println( "whichlinesmatched: " + whichLineMatched<i> );
    } catch(Exception e) {} //end of try
    }

    A small change to roopa_sree's code, this code fails if there are multiple occurences of the search string in the same line. Make this small change to correct it,import java.io.File;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.util.StringTokenizer;
    public class WordCounter {
         public static void main(String args[]) throws Exception {
              if(args.length != 1) {
                   System.out.println("Invalid number of arguments!");
                   return;
              String sourcefile = args[0];
              String searchFor = "good bye";
              int searchLength=searchFor.length();
              String thisLine;
              try {
                   BufferedReader bout = new BufferedReader (new FileReader (sourcefile));
                   String ffline = null;
                   int lcnt = 0;
                   int searchCount = 0;
                   while ((ffline = bout.readLine()) != null) {
                        lcnt++;
                        for(int searchIndex=0;searchIndex<ffline.length();) {
                             int index=ffline.indexOf(searchFor,searchIndex);
                             if(index!=-1) {
                                  System.out.println("Line number " + lcnt);
                                  searchCount++;
                                  searchIndex+=index+searchLength;
                             } else {
                                  break;
                   System.out.println("SearchCount = "+searchCount);
              } catch(Exception e) {
                   System.out.println(e);
    }Sudha

  • Gluegen wrapper returning String or Array

    How can I setup a wrapper function to return a String or
    Array. In my wrapper.gg file I'd like to have something like:
    public function mystrcat(str1:String, str2:String):String
    char *ret = strcat(str1, str2);
    return ret;
    public function myarrayfunc():Array
    int a[10];
    return a;
    Do I need to stuff the data in a ByteArray or something like
    that?

    I've got trouble getting Strings to work within a gg wrapper. I tried adding the following within a gluegen file (note there are no pure c-code blocks, only the pseudo-AS):
    public function getString():String {
        return AS3_String("hello");
    running gluegen with the following:
    gluegen libharu.gg -oc hpdf.c -oas ../src/alchemy/hpdf/hpdf.as -cpackage cmodule.hpdf -package alchemy.hpdf -class hpdf
    and the compiling using:
    gcc hpdf.c -O3 -swc -o hpdf.swc
    But all I get is errors about some conflicting gg_string type and warnings about incompatible pointer types?
    ibharu.gg: In function 'impl_getString':
    libharu.gg:11: warning: return from incompatible pointer type
    libharu.gg: In function 'thunk_getString':
    libharu.gg:10: warning: return makes pointer from integer without a cast
    libharu.gg: At top level:
    libharu.gg:12: error: conflicting types for 'gg_string'
    libharu.gg:10: error: previous implicit declaration of 'gg_string' was here
    However, if I change the code as follows everything compiles fine, and I'm able to use the produced swc in Flex:
    public function getString():Array {
         return AS3_Array("StrType", "hey there");
    So basically, all I've done is returned an AS3_Array instead of AS3_String. Since my C-skills are limited and about 10 years old, I might be missing something very trivial here, but can anyone help me spot what it is? I'm compiling on OS X 10.5.7

  • Search for a String within a document (Word, txt, doc) using JSP, JAVA

    Hi
    I have created a little application that uses combination of JSP and HTML. Users of this application can upload documents which are then stored on the server. I need to develop functionality where I can allows users to search for a string within a document. More precisely, user would type in some string in a text box and application will search all uploaded documents for that string and return the downloadable links to those documents that contains that string. I have never done this before. I was wondering if someone could get me started on this or point me to some thread where this idea is already discussed. Any Jave code exists for searching through documents??
    Thanks for your help
    Riz

    http://www.ibm.com/developerworks/java/library/j-text-searching.html
    http://en.wikipedia.org/wiki/Full_text_search
    Type these parameter in yahoo:+efficient text search
    you will need something like openoffice library to read microsoft word document.

  • Unexpected behavior of spreadsheet string to array function

    Hello,
    I found some weirdness in LabVIEW 2011 that I do not understand. In the attached vi, I provide a one-dimensional spreadsheet string separated by spaces. I use the spreadsheet string to array function to convert this spreadsheet string into an array of strings.
    I ran into problems when I wanted to specify a space character as the delimiter.
    The conversion works as intended, if I do not specify a delimiter (i.e., the default tab delimiter is used). But if I specify the delimiter, only the first element of the spreadsheet string is converted. I do not understand this behavior.
    Thanks for your help.
    Peter
    Solved!
    Go to Solution.
    Attachments:
    Test spreadsheet string to array.vi ‏9 KB

    You don't have spaces in your string. You have tabs and of course the default delimiter works. Right click and select '\' Codes Display and see the \t.

  • Call a function, which name is in an Array of Strings...

    hey all
    i have a simple Temp class (made to check things) in a file called Temp.java with the following definition :
    public class Temp {
         int data1;
         int data2;
         public Temp (){
              data1=0;
              data2=0;
         (here i have get and set functions for both data1 and data 2, and i have the two following functions)
         public void printAdd(){
              System.out.println("Result : "+(data1+data2));
         public void printSubtract(){
              System.out.println("Result : "+(data1-data2));
    }i have another class called Server who has the following simple code :
    public class Server {
          public static void main( String args[] )
               String[] table={"printAdd","printSubtract"};
               Temp game=new Temp();
               game.setdata1(8);
               game.setdata2(4);
              //the following two calls work perfectly
               game.printAdd();
               game.printSubtract();
                   System.out.println(table[0]);
    //but the following does not...
               game.(table[0]);
    }as probably you have understood i am trying to call a function to the object game which name is in the String table... how can i actually made a call game.(THE_VALUE_OF_STRING_IN_AN_ARRAY) ...?

    i want to call the function printAdd() to the game object..
    but i want the program to find out the name of the function to call.. i want to execute the function whose name is at the array in position 0 -> table[0]
    so i want the program to resolve the table[0] to printAdd and the use it and call it on object game...

  • SEARCH function in Adobe Captivate 8 so that the user can search key words within a project?

    Hi, I am wondering if there is a way to implement a SEARCH function in Adobe Captivate 8 so that the user can search key words within a project?

    Hello again
    Click the slide in the film strip, then examine the properties. You name the slide in the properties. And once you name it, the name should appear below the slide in the film strip, Then when you choose to enable the TOC, what you have there pulls in as shown below:
    If you have already constructed your TOC and wish to change this later, repeat the steps of naming the slides. Then click the Reset TOC icon just above the Settings button in the TOC section of the Skin editor to pull in the new names.
    Cheers... Rick

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

  • Function for search string in all table of a particular schema ? (postgres)

    Hi ,
    i want to create a function postgresql, that can able to search a string from all tables.
    I try as below.... please rectify this
    CREATE OR REPLACE FUNCTION search_string(str char(50))
    returnS character varying AS
    $BODY$
    DECLARE
         tempCount bigint ;
    record_v record;
    itemid_v bigint ;
    query varchar;
    return_v character varying := null;
    BEGIN
    for record_v in (select table_name ,column_name
                        from information_schema.columns and data_type in ('character','character varying','text')) loop
    query := 'select count(*) from '|| record_v.table_name ||' where ' || record_v.column_name || ' like ''%' || str ||'%''' ;
         execute query into tempcount;
              if (tempCount >0) then
              return      'l';
              else
              return      '2572';
              end if;
              end loop;
    END;
    $BODY$ LANGUAGE plpgsql VOLATILE
    COST 100;
    in output i need all tables in which string exists :
    like table_name      count_of_string_match

    Mr. singh wrote:
    oracle is the master of all databases - i hope u know
    if any body work on oracle .. he can right any query in any database :)Query maybe. but you were asking about functions. ANSI SQL is a pretty good standard for most normal dbs nowadays. But the procedural extensions differ more. Therefor you should go to a postgress forum to ask there. Or upgrade your database to oracle.

  • Using Excel Active X to Find a String within a column

    I am trying to use ActiveX functions to search for a string within a specific column in excel. And return the row index of that string if a match occurs. Any help on that will be appreciated. I used Read then Compare for each cell in that column, but it is too slow. Maybe a search will be faster.

    Here are some Vi's that will allow you to do a "find" just like doing the edit find function in excel. There is also a vi in there to do a search and replace.
    Joe.
    "NOTHING IS EVER EASY"
    Attachments:
    replace.llb ‏117 KB

  • Search for string and move decimal

    Hello,
    I am trying to write code that will search for a fractional string within an array and convert it from mV to V so it can be properly compared to the other fractional string numbers in the array.
    I have an array that outputs x iterations  each with a minimum and maximum column including several different types of decimal strings (negative/positive with several decimal places) each ending with either mV and V (example string: -725.543mV).
    I then split the array into columns containing the minumum and maximum values of each iteration. I want to compare the minimum values of each iteration and find the most minimum, and do the same thing with the maximum values.
    Unfortunatley the way I'm doing it, when I convert from fractional string to number it removes the V or mV unit label but does not convert the number from mV to V. so it compares -725.543mV with -52.334V as -725.543 & -52.334 thus declaring the mV value the most minimum. I need the program to recognize that mV is less than V or search each array for values labeled with mV and move the decimal place so it is in standard V format.
    The unit label is actually part of the string and not the display (as you can see in the code I've attached) and I understand this is a little tricky with the way I have to do it. But this is a dumbed down chunk of code I will eventually incorporate into my larger program which reads the values and their units from several different types of oscilloscopes. The Scopes output the values as strings as they appear on the screen and don't differentiate between mV and V unless they are told to output the units which just tags them on the end of the string.
    I'm sorry for the large post. SO to sum up I need to search an array to make sure all values have the same units, if they don't I need to convert each value to the proper unit and output the max and min from the resulting array. my code is attached. Thank you for your help.
    Solved!
    Go to Solution.
    Attachments:
    File manipulation.vi ‏15 KB

    crossrulz wrote:
    jcarmody wrote:
    camerond wrote:
    Sorry, Jim, that's not quite right. You forgot to consider significant figures (your third min is not quite right). [...]
    Good catch, but, really?   
    That "Finally!" comes out to -5569492V to me.  Holy crap.  -5.569492MV!  I think there's a problem there.
    Carp! Stupid negative numbers, shouldn't be allowed. Put a piece of duck tape over the place for that negative sign, that'll fix it.
    I'll get back, it's now a matter of principle.
    Jim, how does your algorithm do when there are 8 or 9 sig figs, say -56.9492345mV? (Yep, too lazy to draw it in myself.)
    Cameron
    To err is human, but to really foul it up requires a computer.
    The optimist believes we are in the best of all possible worlds - the pessimist fears this is true.
    Profanity is the one language all programmers know best.
    An expert is someone who has made all the possible mistakes.
    To learn something about LabVIEW at no extra cost, work the online LabVIEW tutorial(s):
    LabVIEW Unit 1 - Getting Started
    Learn to Use LabVIEW with MyDAQ

  • Spreadshee​t String To Array DBL Performanc​e Improvemen​t

    While developing and profiling a batch data-analysis program, I found that the "Read From Spreadsheet File.vi" function was where the majority ofthe execution time was spent.  Digging further, I found the time was spent in the "Spreadsheet String To Array" function.  Obviously I cannot look inside this function, but I wondered if I can somehow speed it up.  Attached is a Vi that illustrates what I came up with as an alternative.
    Basically using "Spreadsheet String To Array" only to split it up to a 2D String Array, and then "Fract/Exp String to Number" to convert the strings to numbers.
    It consistently runs in just over 60% of the time of using Spreadsheet String To Array on it's own to do the conversion.
    I am curious as to why using the two functions is quicker than just the one on it's own? Perhaps NI can improve the internals a bit?  Or perhaps it is not a fair comparison?
    Labview 8.6f1 Win XP SP2
    Message Edited by pauldavey on 03-25-2009 02:55 PM
    Attachments:
    Speed Test Spreadsheet String to Array.vi ‏26 KB

    Adding a couple of other conversions to test against i noticed that:
    1. Scan from string through a double loop was the slowest
    2. Scan Value was slightly faster
    3. Direct conversion through Spreadsheet to array as in OP
    4. 2-step convert through Fract/Exp.
    Could it be that Spreadsheet to array uses Scan Value internally?
    /Y
    LabVIEW 8.2 - 2014
    "Only dead fish swim downstream" - "My life for Kudos!" - "Dumb people repeat old mistakes - smart ones create new ones."
    G# - Free award winning reference based OOP for LV

  • How to search a string in some folder.

    Hi ,
    In my application users will upload some pdf,xls files to server. files will be saved in server. From the front end can search on all files with some specific string. If that string is there in any of the file, user has to get link to download that file and the text just before and after that user string. Its like how we get in google. This type of search we need to implement, Could any one please let me know how to implement, any free API are there in java. Please its urgent, help on this.
    Thanks
    Mohan

    user594301 wrote:
    I have 2 columns in a table. entry_no and msg_txt. entry_no is number(12) and msg_txt is LONG. I want to search one string in msg_txt. How can I write a query for this ?You can't write a query for this. The only thinks you can do with a long in a query is put something in and take it out again - with diffiuclty, usually.
    You can write a PL/SQL function to do this for you if necessary. The function will have to perform the search directly if the long < 32760 bytes or use DBMS_SQL to break the LONG up into 32760 byte segments that can then be manually searched. If you are lucky someone has done this already and posted the code online. Either way the solution will be slow and probably painful to implement.
    If possible convert your data to a CLOB and use DBMS_CLOB to find the data you need.

  • Apparent inconsistency of "spreadsheet string to array"

    System: LabView6.1, XPpro, 512MB, 2.4GHz
    I have a sub-vi which I call to read a single column of data from a large CSV file. Files can be >500000 rows with 4-8 cols (ie. 15-30MB). The sub-vi uses "Read File", with byte stream type unwired, to return a string. This string is then passed to "spreadsheet string to array" (SStA), to obtain a 2D array. "Index Array" is then used to obtain the required data column.
    If I wire the format string of SStA with %f, and the array type with a 2D double, the sub-VI takes about 8 seconds every time I call it.
    If I wire format string with %s, and array type with 2D string (and convert to a double later, after index array), the sub-VI takes over 50s the first time it is c
    alled, but only about 1s on each subsequent call.
    The bottle neck is ONLY at SStA. I am not explicitly preallocating any arrays.
    Can anyone explain what LabView is doing internally with respects to memory allocation? Why is the second routine slow on the first call only, and subsequently considerably faster than the first routine? Is there any alternative way of "priming" the second sub-vi so it is not slow on the first call? I guess reading only subsets of data at a time might help, but I'd still like to understand what is going on with the current approach.

    Roo Payne wrote:
    > Can anyone explain what LabView is doing internally with respects to
    > memory allocation? Why is the second routine slow on the first call
    > only, and subsequently considerably faster than the first routine? Is
    > there any alternative way of "priming" the second sub-vi so it is not
    > slow on the first call? I guess reading only subsets of data at a time
    > might help, but I'd still like to understand what is going on with the
    > current approach.
    Basically NI seems to have added some performance optimization with
    internal caching to the Spreadsheet String to Array function in the case
    of String outputs. Without it it would always take 50 seconds. If the
    input string does change significantly it probably won't be such a huge
    speed up anymore.
    For numeric type outputs no caching has been added and wouldn't help
    that much in comparison.
    Rolf Kalbermatter
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Issues with spreadsheet string to array

    Hi, I have a spreadsheet string (tab delimited) and I am trying to convert it into an array of double with 6 digits of precision after the decimal point. However, as shown in the attached example, the function "spreadsheet to array" is not giving me the desired digit of precision (only 2 after decimal point). I have tried almost everything and I am frustrated with this function. CAN SOMEONE PLZ HELP ME ??
    Attachments:
    Block diagram.png ‏13 KB
    String to array double.vi ‏10 KB
    Panel.png ‏28 KB

    I have no LV 8.x installed, so I can't check your Code. But it might be your settings for the indicator. In LV 7.1 it defaults to 6 significant digits, that means the reading is 12345,6789 but (only) your indicator displays 12345,6.
    Right click on your indicator (Front Panel) and go to formatting.
    Felix
    www.aescusoft.de
    My latest community nugget on producer/consumer design
    My current blog: A journey through uml

Maybe you are looking for

  • Can I embed fonts in exported Word docs in 09

    As it says. Can I embed fonts in an exported DOC type document, in Pages 09, or 5.2 for that matter? thanks

  • Having problems with text, some images are not displaying properly

    when opening an image( as screenshot) in firefox support forum, the close button is not showing instead a number code is shown in a box

  • Profile manager w/o Apple Push Certification

    Hello all. Is it possible to use Profile manager without using Apple Push Certification? The Mac Pro running Lion Server has no Internet access but i want to use it to manage network accounts for the lab (all iMac and Mac Mini systems). Can this be d

  • Downside to moving iTunes library to external HD ?

    I am using Leopard. I have an iPod and an Apple TV. Both of their hard drive capacities exceed my 3-year old PowerMac desktop. Thus, I am always battling with "Your startup disk is almost full." I am curious about the performance implications if I mo

  • Initial View Settings Ignored

    I've created a PDF and trying to control the inital settings in Document Properties/layout and magnification...But, after saving the settings and when the document is opened, they are ignored. I know I've been able to do this before, but not now. I'm