Comparing a string with a stored list(or array or ...)

Hi all. I am trying to figure out the best way to do the following:
I need to store serveral strings into a structure so that I can compare them against a string and see if the string is contained in the previously mentioned strings.
I want to make the structure static, as it should not change, and I only need one instance of it, but I can't seem to come up with something I like. I was thinking of just using a string array and then running a loop comparing each position in the array to my string, but that seems inelegant to me for some reason. Anyone have any thoughts, or is that pretty much the best I am going to do ?
thanks in advance.

I might be inclined to use an ArrayList instead of an array of Strings, which would allow me to use use the contains method to do object comparisons so my code would end up looking more like this.
        ArrayList list = new ArrayList() ;
        list.add("Fred") ;
        list.add("Barney") ;
        list.add("Wilma") ;
        list.add("Betty") ;
        if(list.contains("Barney"))
            System.out.println("Hey Barney") ;
        else
            System.out.println("Absence of Barney detected") ;
        }But it's still doing the same thing you're describing under the hood.
Hope this helps,
PS.

Similar Messages

  • How to compare German strings with umlaut

    hi
    here is a solution for the problem to compare German strings containing umlaut, which I faced and where I did not find any solution yet!
    The right thing is to use the RuleBasedCollator class and define the additional rules (concerning the umlaut) by yourself and setting the strength of the rule interpretation to PRIMARY!
    Here is the code that works:
    public class UmlautTest { 
    public static void main (String args[]) {    
    String st1 = "Daettenb�ck";
    String st2 = "D�ttenbueck";
    String myRule = "< ae,�,AE,� < oe,�,OE,� < ss,�,SS < ue,�,UE,�";
    RuleBasedCollator myrbCol = null;
    try {
    myrbCol = new RuleBasedCollator(myRule);
    } catch (ParseException e) {
    e.printStackTrace();
    myrbCol.setStrength(Collator.PRIMARY);
    if (myrbCol.compare(st1, st2) != 0) {
    System.out.println("myrbCol: NICHT gleich!");
    } else {
    System.out.println("myrbCol: Gleich!");
    I hope that I could help anyone with that
    nocomm

    The � should be of course replaced by the missing umlaut!
    Sorry, but I didn't preview the topic!
    nocomm

  • Comparing a String with array elements

    i need some help as to how to compare an individual String with each item of a String array.
    so far i have:
    StringTokenizer drinksOrder = new StringTokenizer(orderLine, "\r");
    while (drinksOrder.hasMoreTokens())
         for (int index = 0; index < NUMBER_OF_DRINKS; index++)
                 barcode = drinksOrder.nextToken();
                        if (barcode.equals(barcodes[index]))
                                     name = drinks[index];
                                     price = prices[index];
                                     status = drinkStatus[index];
              orderedDrinkBC[j] = barcode;
                                              orderedDrinkName[j] = name;
                                              orderedDrinkPrice[j] = price;
                                              orderedDrinkStatus[j] = status;
              j++;
              break;
    [\CODE]
    At the moment, no Strings are being put in the orderedDrinkBC, orderedDrinkName, orderedDrinkPrice
    and orderedDrinkStatus arrays. the code seems to be failing on the 'barcode.equals(barcodes[index])
    part at the moment.
    any help would be appreciated
    cheers
    david                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Do this instead (next time post your code in lower case code tags):
    StringTokenizer drinksOrder = new StringTokenizer(orderLine, "\r");
    while (drinksOrder.hasMoreTokens())
      barcode = drinksOrder.nextToken();
      for (int index = 0; index < NUMBER_OF_DRINKS; index++)
        if (barcode.equals(barcodes[index]))
          name = drinks[index];
          price = prices[index];
          status = drinkStatus[index];
          orderedDrinkBC[j] = barcode;
          orderedDrinkName[j] = name;
          orderedDrinkPrice[j] = price;
          orderedDrinkStatus[j] = status;
          j++;
          break;
    }

  • URGENT! I need to compare a String with a line in a .txt file

    I'm a college student and I have a very simple question i guess. I need to write an if procedure which compares if a line of a .txt file is equal to something, but I just don't know how to do it. HELP!

    What specifically are you asking for? How to compare two strings?
    String s = "cat";
    String t = "Cat";
    if (s.equals(t))
       System.out.println('They are equal');    // does not print out
    if (s.equalsIgnoreCase(t))
       System.out.println('They are equal');    // prints out

  • Comparing a String with another one from a file

    I read a line from a .txt file using in.readLine();
    How do i make comparesson to see if the word in the file is "zoo" ?
    String read;
    read = in.readLine();
    System.out.println(read) --- > prints "zoo"
    if (read == "zoo")
    System.out.println("it works");
    else
    System.out.println("doesn't work");
    and this code prints out "doesn't work" even tho zoo is same as zoo... how do i fix this?

    Change if (read == "zoo") to:
    if(read.equals("zoo"))You want to compare the String's content, not the reference.

  • How to compare a string with integer in jsp

    I have a field in database called as enddate
    i m trying to split the entire date and get date,month and year
    once i store the date in a variable called as fmdate which is string,
    i need to compare it with another integer.
    how can i compare it..heres my code
    stdate=RS.getString("start_date");
         fmdate=stdate.substring(8,10);
         fmmonth=stdate.substring(5,7);
         fmyear=stdate.substring(0,4);
    and this is where i want to compare the value of j to fmday...
    <td class="btext" valign="center">Day<select name="fmday">
    <%
    for(int j=1;j<=31;j++)
    String s;
    parseInt(s)=j;
    if (fmdate.equals(s))
    %>
    <option value="<%=j%>"><%=j%></option>
    <% } else { %>
    <option value="<%=j%>"><%=j%></option>
    <%
    } %>
    </select>
    pl help me...
    Thanks Srini

    j is an int, so you're just adding 0, not concatenating. Perhaps something like this would work.
    <%
      for(int j=1;j<=31;j++)
         String date = String.valueOf(j);
         if(j <= 9) {
            date = 0 + date;
         if (fmdate.equals(date)) {
    %>
      <option value="<%=date%>"><%=date%></option>
    <%
         } else {
    %>
      <option value="<%=date%>"><%=date%></option>
    <%
    %>Uhm, I assume there should be a 'selected' or something in one of the option tags?

  • How to compare two strings with each other?

    Hello,
    I have modeled a formular which has a radio group and a button. Furthermore, I have one result state corresponding to each option in the radio group.
    In order to determine which result state actually is to be reached I want to attach a condition to each flow to the result states that tests which option has been chosen.
    Which operator can I use for writing these conditions? I have tried the "like" operator as well as the "==" operator but neither seems to work.
    I have written something like:
    =LIKE(@decision, 'option a')
    as well as:
    =(@decision=='option a')
    What am I doing wrong here?
    Thank you very much
    Alexander

    Hi Alexander,
    Could this be an Upper/Lower case issue.
    I tried the following expression
    =(@TXT1=="opt a")
    and it worked.
    If you want your expression to ignore case you should use this expression:
    =(UPPER(@TXT1)==UPPER("opt a"))
    In case you're not sure what is the exact string in the field (@decision) you can always use the PROMPT action to display the field's value.
    Regards,
    Udi

  • I am trying to make a call to a dll to have labview return a buffer filled with data stored in an array. The proble

    m that I am having is that to do this I need to fill two different structures, one containing a pointer to a double, which I don't think I can do without perhaps a wrapper function. The biggest problem is that I don't know how to even go about doing this.I have two structures that I need to fill in order to read a block of data from a given DLL which are
    typedef struct CHBL_ORDER_T {
    INT32 lBlock; // block number, set by user (typical 0)
    INT16 sChan; // channel number, set by user
    UINT16 usFlags; // only DATA_1OFN at the moment
    INT32 lChSR; // channel sampling rate, returned by open
    INT32 lFirstMP; // BSR MP not greater than "open sta
    rt"
    INT32 lBuffLen; // required CHSR based buffer size
    INT32 lIncr; // distance between two buffered values
    UINT16 usMask; // Mask used before Shift
    INT8 chShift; // number of right shifts
    } CHBL_ORDER, *PCHBL_ORDER;
    typedef struct CHBL_FETCH_T {
    double *pdblMin; // min or 1 of n array
    double *pdblMax; // max array (either solo or along with MINMAX
    INT32 lPos; // (set by user), returned by fetch
    INT32 lNum; // (set by user), returned by fetch
    } CHBL_FETCH, *PCHBL_FETCH;
    I am trying to do the data block access with labview on page 18 of the attached pdf document.
    I also have a c code exapmle attached in the zip file, the function in c i am trying to do is in Sample2Dlg.cpp
    if anyone can help me out I would greatly appreciate it.
    Attachments:
    BS_Toolbox_(Ford).PDF ‏160 KB
    sample2.zip ‏55 KB

    m that I am having is that to do this I need to fill two different structures, one containing a pointer to a double, which I don't think I can do without perhaps a wrapper function. The biggest problem is that I don't know how to even go about doing this.I believe you are right about needing to create a wrapper DLL. To do this, just create a DLL which includes a function that accepts a double. Then, it uses this to make a pointer to that double and send it to your original DLL. When that function returns, you return this info to LabVIEW in form of a regular double. Basically, there is just one more layer of code which you use for translation between LabVIEW and the DLL you are currently using. You need to create that layer.
    J.R. Allen

  • In LabVIEW, how to put a string of numbers stored in the array?

    That is the question.Please.

    What is the data format.  Comma delimited string of ASCII numbers?  Please provide an example to clearly show what you currently have and what it is that you want.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Comparing 2 strings

    hi
    i have an application, in which, i am taking a string as input from th user(thru a JOptionpane.inputDialog)
    now, i have to compare this string with various other values present in an already stored file.
    please sugest a method to do so.
    the file has different values appended one after another , separated by a space.
    the problem is, i want to parse the entire file, to look for the required value.
    please help.
    thank u.

    Parse the file once using a thread as soon as the program has started running.
    If you just want to know whether or not a value is in the file then just store the values from the file in a Set (java.util.HashSet).
    If you want to associate a value with some other information then store the (key,value) pairs read from the file in a Map (java.util.HashMap).
    If you want to record information about what the user has entered then again store the file informaion in a Map but make the value an object of your own making.

  • XML validation with DTD stored in String object

    Does anyone know if this is plausible......
    I am trying to validate some XML with a DTD... easy enough, right? The catch is that the dtd is NOT stored in a file somewhere and is also not declared in the XML to be validated. It is stored in a String object (as is the XML file to be validated).
    To clarify - I want to do something like this... but not sure how to incorporate the DTD.
    String dtd = // dtd definition here
    String xml = // xml text here (no URI at the top)
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler();  // DTD handler??
    parser.parse(new InputSource(new StringReader(xml.toString())), handler);any help would be greatly appreciated.
    thanks in advance,
    Terrance

    I guess it makes the most sense to make the dtd local to the xml. Therefore I would only have one string with both the xml contents and dtd contents. That is how I am going to approach this unless I hear something different.

  • Comparing Collection object with a string

    Hi everyone,
    There is my problem: I have a program that generate all possible combinations of a certain number of letters for example: -ABC- will gives A, B, C, AB, AC, BC, ABC. Everything is fine at this point. But then the user can input a string like "AB" and I have to tell him if this string is contained in the generated set. My set is in a Collection, but when I used : LetterCombination.Contains(TextString), it returns always false. Even if I know that the string is contained in the set.
    Here is the code to generate the set:
    public class Recursion
         Collection LetterCombination;
    /*String Letters is the letters which I have to generate the combination, and
    the LetterNumber is the number of letters contained in my string.*/
         public Recursion(Set ItemLetters, String Letters, int LetterNumbers)
              ItemLetters = new TreeSet();
    String[] Token = Letters.split(" ");
    /*Adding the letters in the TreeSet*/
    for (int i = 0; i < LetterNumbers; i++)
         ItemLetters.add(Token);
    LetterCombination = BuildLetterSet(ItemLetters);
    private Collection BuildLetterSet(Set ItemLetters)
    Set NotUsedYet = new TreeSet();
    Set thisPowerSet = new TreeSet();
    Collection Letterresult = new ArrayList();
    NotUsedYet.addAll(ItemLetters);
    BuildByRecursion(NotUsedYet, thisPowerSet, Letterresult);
    return Letterresult;
    private void BuildByRecursion(Set notUsedYet, Set thisPowerSet, Collection result)
    if(notUsedYet.isEmpty())
    if(!thisPowerSet.isEmpty())
    Set copy = new TreeSet();
    copy.addAll(thisPowerSet);
    result.add(copy);
    return;
    Object item = notUsedYet.iterator().next();
    notUsedYet.remove(item);
    BuildByRecursion(notUsedYet, thisPowerSet, result);
    thisPowerSet.add(item);
    BuildByRecursion(notUsedYet, thisPowerSet, result);
    thisPowerSet.remove(item);
    notUsedYet.add(item);
    And if I print out the LetterCombination collection, it gives me:
    [C]
    [B, C]
    [A]
    [A, C]
    [A, B]
    [A, B, C]
    Which are the good combination needed. But I really don't understand how to compare this collection with the string entered by the user.
    I'm really lost. can somebody help me! Thanks in advance...

    You don't show where you call this constructor, or what your arguments are:
    public Recursion(Set ItemLetters, String Letters, int LetterNumbers)
       ItemLetters = new TreeSet();
       String[] Token = Letters.split(" ");
       /*Adding the letters in the TreeSet*/
       for (int i = 0; i < LetterNumbers; i++)
          ItemLetters.add(Token[ i ]);
       LetterCombination = BuildLetterSet(ItemLetters);
    }But, the constructor doesn't make sense, anyway. itemLetters is immediately set to a new TreeSet, so whatever you passed in (if anything) for the first argument is unchanged by the constructor (and the new TreeSet is lost when you finish the constructor). Also, you split your input Letters on space, but rely on LetterNumbers for the length of the split array (which may or may not be accurate). Why not do a 'for' loop testing for "i < Token.length", and eliminate LetterNumbers parameter? Your input for the second parameter to this constructor would have to be "A B C D" (some letters delimited by spaces). Your constructor only needs one parameter--that String.
    The capitalization of your variables doesn't follow standard coding conventions. Your code is hard to read without the "code" formatting tags (see "Formatting Tips"/ [ code ] button above message posting box).

  • How to compare array of String with column of a table

    Hi,
    i have a array of string(say array is of length 1000). I want to
    compare those string in array with one table column
            - whether that table column has a string
                            if yes
                                            do nothing.
                            if no
                                            then insert that string into table.
            - whether table has obsolete row i.e, the one present in table and
    not in array
                            then delete that row.
    How do i go about this, because i see, it is not feasible to loop
    through array and search table to find new string OR loop through each
    row from table to find some obsolete row
    How can i accomplish this task more feasibly(without running query for
    each string, for comparission)? Is there any way to find this kind of
    problem. I would have been easy if i had to compare two tables(with
    UNION and INTERSECT), but it is not the case.
    thanks,
    kath.

    I'm not sure, whether I understand your problem correctly. Only two comments:
    - if both arrays are sorted, all can be done running exactly once simultaneously through both arrays.
    - if the column is marked as UNIQUE, all column strings will be different. I.e. you cannot insert the same string a second time.
    Regards  Thomas

  • Compare two strings in an array

    Hello!
    Please feel free to give me hints, but do not give me any code.
    Ok, here is what I am trying to do, I whant to compare my input string whith strings allready stored in the array. If my input string equals any of the allready excisting strings, a error wil show upp, otherwise store the new string in next avalibal position. I do not seem to get the method right for comparing the strings. here is the method I have written so far, please take a look and give me a hint, but no code. :)
    //Check if a user already excists     
    public void compareNames (People in_array [], String in_name) {
              for (int i=0; i<value.peopleCount; i++) {
                   if (in_name.equals(in_array.getPeople())) {
                   System.out.print("The user already excist, please chose another name");
    }value.peopleCount is an global count value for people arays.
    getPeople get the name from the people class.
    Martin                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    A couple notes here.
    The name compareNames() is misleading if it is going to do what you described. A comparison will generally not have side-effects like outputting error messages to the console or adding new items to an array. It would be better if you called the method addIfNew(), and returned a boolean indicating whether the name was new or not. The caller would then be responsible for displaying an error message if the method returned false.
    I also suggest you use a List such as ArrayList instead of an array, otherwise you will have to resize and copy your array every time you add something to it that exceeds the array size, and will allow you to do away with the global peopleCount.

  • How do i compare Nodes on a home made List?

    This is for one of my classes,
    I have this .java's:
    ******** Nodo.java ( node ) ********
    public class Nodo{
    public T t;
    public Nodo s;
    public Nodo(){
    t=null;
    s=null;
    }******** Lista.java ( List ) ********
    public class Lista{
    private Nodo inicio;
    public Lista(){inicio=null;}
    //This method is supossed to add nodes and keep them ordered ( ASC )
    public void ordenaAscendente(T v){
    Nodo temp =new Nodo(),recorre=inicio;
    temp.t=v;
    if(recorre == null)insertaInicio(v);
    else{while(recorre.s != null){if(!(recorre.t.compareTo(temp.t)<0)){temp.s=recorre;break;}}}
    }******** Articulo.java ( Elements to be inserted on the list ) ********
    public class Articulo implements Comparable{
    private int clave;
    private String nombre,tipo;
    private double costo;
    public int compareTo(Articulo a){if(clave==a.clave)return 0; else return ((clave>a.clave)?1:-1);}
    public String toString(){return ("Clave:"clave"\tNombre:"nombre"\tTipo:"tipo"\tCosto:"+costo);}
    }and im stuck with this error:
    Lista.java:17: cannot find symbol
    symbol : method compareTo(java.lang.Object)
    location: class java.lang.Object
    else{while(recorre.s != null){if(!(recorre.t.compareTo(temp.t)<0)){temp.s=recorre;break;}}}     
    ^
    Please Help, my deadline is tomorrow at 10pm.
    P.S. The teacher said that something was missing on the Lista class declaration, probably an interface.
    THX

    [http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html]
    Newlines and indentation don't cost money, and not using them makes your code next to unreadable. This:public void ordenaAscendente(T v){
    Nodo temp =new Nodo(),recorre=inicio;
    temp.t=v;
    if(recorre == null)insertaInicio(v);
    else{while(recorre.s != null){if(!(recorre.t.compareTo(temp.t)<0)){temp.s=recorre;break;}}}
    }should be   public void ordenaAscendente(T v) {
          Nodo temp = new Nodo();
          temp.t = v;
          Nodo recorre = inicio;
          if (recorre == null) {
             insertaInicio(v);
          } else {
             while (recorre.s != null) {
                if (!(recorre.t.compareTo(temp.t) < 0)) {
                   temp.s = recorre;
                   break;
       }That might help you (and others) see exactly where the error is arising. Either a cast to a Comparable, or proper use of generics, is indicated here.
    db

Maybe you are looking for

  • Error while applying the  R12.PJ_PF.B.DELTA.5

    Hi, The patch session failed when it was running pablu.ldt FAILED: file pablu.ldt on worker 1 for product pa username APPS. FAILED: file b9281321lu.ldt on worker 2 for product pn username APPS And the log /ebs/DEV/app/apps/apps_st/appl/admin/DEV/log/

  • Find Purchase Order ADF service

    Hi, Hoping you can help with the search criteria on the FIND service. I am able to retrieve an entire PO and all child objects using the service.  When I try to reduce this result set to only return the PO_LINE_ID's, the service seems to ignore my ch

  • Oracle Email Server 5.2 -- Email Server Understanding & Planning

    Soon we plan to install Oracle Email Server 5.2 on our Compaq machine running Tru64 Unix version 5.1. I was going through the "Oracle eMail Server Release Notes Release 5.2 for Compaq Tru64 UNIX" (A87547-01) manual. The manual mentions about "Oracle

  • Nonlinear Curve Fit and using static data

    I am trying to fit data to a 2D function using the Nonlinear Curve Fit VI in Labview 8.2.1, but I would like to also include 2 parameters that I don't want to be optimized.  I cannot directly use constants since every time I run the fitting I need to

  • I can't attach files from Dropbox in Yahoo Mail.

    When I try to use the "Share from Dropbox" option to attach files when sending emails from Yahoo, the Dropbox window starts to open but just contiunes with the circle icon.