String Array Search

Hi all,
I have two arrays
String st[]={"abc","xyz"};
String ab[]={"abc","def","egh","oki","xyz","poi"}
i want to check the values of the first array with the values of the second array..so i want the values in the second array which are not equal to the values in the first array..
Can anyone help please...
Thanks in advance..

Hi
In case of string arrays we cannot decrease the size dynamically.But i can fulfuill ur requirement as follows.Iterate through the arrays and find the equal element in ur second array ,and make it is as empty.That means just we are making the value empty and we are not removing the location.
String st[]={"abc","xyz"};
          String ab[]={"abc","def","egh","oki","xyz","poi"};
          for(int i=0;i<st.length;i++){
               for(int j=0;j<ab.length;j++){
                    if(ab[j].equals(st)){
                         ab[j]="";
          for(int i=0;i<ab.length;i++){
          if(!(ab[i].equals(""))){
          System.out.println(ab[i]);
But Using (Lists) ArrayList we can increase or decrease the size dynamically.

Similar Messages

  • Searching two dimensional string arrays

    Hello, I'm very new to Java. I would like some advice on the code below. What I'm trying to do is: I want the user to enter a 9 digit number which is already stored in an two dimensional array. The array is to be searched and the 9 digit number and corresponding name is to be printed and stored for future reference. Something is wrong with my array checking. If I enter the nine digit number, the program errors and asks me again for the number. If I enter 0-4, I receive an output. I just don't know how to compare string array values. Could someone please help me with this?
    import java.io.*;
    import java.util.*;
    public class SocialSn2
         public static void main(String args[]) throws Exception
              boolean validSSAN = false;
              Ssn(validSSAN);
              if (validSSAN)
                   //Ssn(false);//write the code here to continue processing
         }//end main
         public static void Ssn(boolean Validated)
              String[][] employees =
                   {{"333333333", "Jeff"},
                   {"222222222", "Keith"},
                   {"444444444", "Sally"},
                   {"555555555", "Kaylen"},
                   {"111111111", "Sheriden"}     };
              boolean found = false;
              while (!found)
                   System.out.println("Enter the employee's Social Security number.");
                   BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                   try
                        String line = in.readLine();
                        int input = Integer.parseInt(line); //added
                        found = false;
                        for(int j = 0; j < 5; j++)
                        if(input >= 0 && input <= employees.length)
                             //if(employees[j][0].equals(input))
                                  //System.out.println(employees[input][0] + employees[input][1]);
                                  found = true;
                             System.out.println(employees[input][0] + " " + employees[input][1]);
                   catch (Exception exc)
                        System.out.println("error");
                        found = false;
              Validated = found;
         }//end Ssn
    }//end class

    There seems to be some problem with your loop for checking those values
    if you had used System.err.println() in your catch block you would see that you were getting an ArrayIndexOutOfBoundsException
    The following works for me.
    import java.io.*;
    import java.util.*;
    public class SocialSn2
    public static void main(String args[]) throws Exception
    boolean validSSAN = false;
    Ssn(validSSAN);
    if (validSSAN)
    //Ssn(false);//write the code here to continue processing
    }//end main
    public static void Ssn(boolean Validated)
    String[][] employees =
    {{"333333333", "Jeff"},
    {"222222222", "Keith"},
    {"444444444", "Sally"},
    {"555555555", "Kaylen"},
    {"111111111", "Sheriden"} };
    boolean found = false;
    System.out.println(employees.length);
    System.out.println(employees[0].length);
    while (!found)
    System.out.println("Enter the employee's Social Security number.");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    try
    String line = in.readLine();
    //int input = Integer.parseInt(line); //added
    found = false;
    for (int i=0; i< employees.length;i++)
         if(employees[0].equals(line))
         System.out.println(employees[i][0]+" "+employees[i][1]);
         found = true;
    catch (Exception exc)
    System.err.println(exc);
    found = false;
    Validated = found;
    }//end Ssn
    }//end class

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

  • Exporting a String Array to an HTML file

    Hey everyone..I'm currently making lots of progress in my project...but right now I've been trying to make a button that exports my search results to an html file...basically what I've made is a search engine to search webcrawler files...
    The result list I get (which is actually a string array), I want to export to html so I can open that html file and find all the links that were found in the search I made..What I have so far is this, but it's not working yet, any help? :
        private class exportListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                String[] result = parent.getResult();
                if(result == null)
                    return;
                JFileChooser chooser = new JFileChooser();
                chooser.setAcceptAllFileFilterUsed(false);
                chooser.setFileFilter(new HtmlFileFilter());
                chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                int returnVal = chooser.showSaveDialog(parent);
                if(returnVal == JFileChooser.CANCEL_OPTION)
                    return;
                File fl = chooser.getSelectedFile();
                String path = fl.getPath() + ".html";
                searchIF.exportResultAsHtml(path);
                System.out.println(path);
        private class HtmlFileFilter extends FileFilter
            public String getDescription(){return "Html";}
            public boolean accept(File pathname)
                String name = pathname.getPath();
                //Just checking to see if the filename ends with html.
                if (name.toLowerCase().substring(name.lastIndexOf('.') + 1).equals("html"))
                    return true;
                return false;
            }

    Actually..nevermind, sorry.

  • Getting lenght of String array

    Hi,
    How can i find the lenght of a string array, i have used length method to calculate length of single string value,e.g
    String value = "test"
    int length = value.length()
    Now i want to calculate length of a string array.e.g
    String csv_values = "test,by,random"
    String[] str = csv_values.split(",")
    int lenght = str.length()
    As you can see i want to calculate total number of entries in an array after i split it dynamically.
    Currently it is giving me exception, "Unable to parse exception; Undefined method: length for class: [Ljava.lang.String]"
    Thanks

    This is a tricky one.  An Array has a length property, unlike a String which has a length method.
    So...
    int length = str.length
    Anthony Holloway
    Please use the star ratings to help drive great content to the top of searches.

  • Large string array in 6.1 is extremely slow

    Good day all,
    While this is in to tech support at NI, I wanted to see if anyone else has encountered it.
    I am upgrading from 6.0.2 to 6.1. Several large (2500 rows by 250 columns or larger) string arrays are used as inputs into subvi's. Under 6.0.2, these functions run in tenths of seconds, while under the converted 6.1 vi's they run in 20 seconds or more!
    Tracing back using probes, the problem is occurring at the point of the input. It is appears that the array is taking many seconds to copy from the input to the wire on the diagram.
    Array controls generated in 6.1 (not converted from 6.0.2) seem to function just fine. Using a save with options... to convert back to 6.0.2, the vi's again function in tenths of
    seconds.
    Anyone have any ideas?
    Thanks!

    I hear what you're saying about legacy code...
    Something you might want to be looking at for the future is migrating to a structure where the data is stored in a 1D array, where each element is a cluster contain the data that's now in a single row. This would be the most straight-forward change, but could make getting at the data tricky, depending on how you need to be able to search it.
    Alternately, you could have a cluster containing arrays of each of the row values.In this structure element 0 of all the arrays is the first "row", element 1 of the arrays is the second "row" and so on. This structure at first blush looks more complicated, but it's really not, plus it would allow you to use any value (or combination of
    values) to search for a specific row without a lot of parsing.
    If the data that is in the example VIs you posted is typical, either of these changes would be advantagous because it looks like there is a lot of reptative data that might be able to be encoded in an enum. Plus storing numbers as numbers often reduces the memory required and produces a predictable memory footprint (an I32 will always take-up 4 bytes per value regardless of how large of small the number is). My sense is that the variability of the string size is what's killing you.
    One thing that would make this sort of dramatic change somewhat easier is that because you are changing the basic datatype of the interface, you aren't going to have to worry about finding all the places the change will effect--the wires will be broken.
    If you ever decide to take this on, give a hollar.
    Mike...
    Certified Professional Instructor
    Certified LabVIEW Architect
    LabVIEW Champion
    "... after all, He's not a tame lion..."
    Be thinking ahead and mark your dance card for NI Week 2015 now: TS 6139 - Object Oriented First Steps

  • Finding the no of occurences of a string in a string array

    hi
    I have a string array which contains different strings say
    for eg date
    [21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 21/08/2008, 22/08/2008, 22/08/2008, 22/08/2008, 22/08/2008, 22/08/2008] etc.
    for eg names
    [coverage, search, search, combined-search, documentService, expand-term, id-mapping, citation, class, corporate-tree, document-update, coverage, coverage, search, search, combined-search, documentService, expand-term, id-mapping, citation, class, corporate-tree, document-update, coverage]
    i need to find out the count of a particular date or name in the string array.
    Also i will not be knowing what is the value that will be present in that string array.
    the values are dynamic. please help to solve this.
    thanks in advance
    Mohan

    In the same way use for date,names and other as required by you..sample code for nameimport java.io.*;
    public class Test {
         public static void main(String args[]) throws Exception{
             int cnt=0;     
                   String name[]={"coverage","abc","def","coverage", "search", "search"};
              BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
              System.out.println("enter name");
              String rv=br.readLine();
         for(int i=0;i<name.length;i++){
              if(rv.equals(name)){
                   cnt++;
    System.out.println("Name occured "+cnt+" times");

  • How do I strip off a time format off of a string array

    How do I strip off a the first part of a time format out of a string array. The following is what it looks like
    14 April 2008 10:00:00.000, 30.000,128.591,-145.839
     "       "      "     10:00:01.000, "              "              "
    I tried the read from speadsheet file first. I tried lower level VIs. There must be something simple I am just missing.

    Search for the first comma and take the data before it.
    Message Edited by Ravens Fan on 12-10-2008 04:50 PM
    Attachments:
    Example_VI_BD.png ‏2 KB

  • Simpler way to sort 2-d string array?

    I have a long 2d string array, and I would like to sort by the 2nd value. It originates as:
        public static final String names[][] = {
         {"000000", "Black"},
         {"000080", "Navy Blue"},
         {"0000C8", "Dark Blue"},
         {"0000FF", "Blue"},
            {"000741", "Stratos"},
         {"FFFFF0", "Ivory"},
         {"FFFFFF", "White"}
        };As you can see, they are pre-sorted by the hex values. That is useful for part of the app.
    There are 1,567 entries. I would like to alphabetize the color names and place them in a list widget. I need to keep the associated hex color values with the name values. All I can think of to do something like:
    1) make a temporary long 1-d string array
    2) fill it by loop that appends the hex values to the name values: temp[i] = new String (names[1] + names[i][0])
    3) sort temp[] with built in Java sort
    4) make a permanent new string array, hexValues[] for the hex values
    5) copy the last 6 characters of each item to hexValues[]
    6) truncate the last 6 characters of each item in temp[]
    7) build list widget with temp[]
    Is there a more elegant way? What I'd really like to do is build a 1-d array of int's, with the values representing the alphabetized locations of the names. However, I don't see any built-in which would do that kind of indirect sort.
    Second question -- Can the backgrounds of each item in a list widget be a different color? Ideally the list would show the color name in black or white, and the its color value as background. Specifically, I'm trying to build the list accomplished by the Javascript code here:
    * http://chir.ag/projects/name-that-color/
    and add it to my Java interactive color wheel:
    * http://r0k.us/graphics/SIHwheel.html
    BTW, I have converted his name that color Javascript (ntc.js) to a native Java class. It is freely distributable, and I host it here:
    * http://r0k.us/source/ntc.java
    -- Rich
    Edited by: RichF on Oct 7, 2010 7:04 PM
    Silly forum software; I can't see what made it go italic at the word new.

    I am implementing a sort infrastructure along the lines of camickr's working example, above. Part of my problem is that I am new to both lists and collections. I've tried searching, and I cannot figure out why the compiler doesn't like my "new":
    public class colorName implements Comparable<colorName>
        String     name, hex;
        int          hsi;
        static List<colorName> colorNames;
        public colorName(String name, String hex)
         float     hsb[] = {0f, 0f, 0f};
         int     rgb[] = {0, 0, 0};
         int     h, s, b;     // b for brightness, same as i
         this.name = name;
         this.hex  = hex;
         // Now we need to calculate hsi,
         this.hsi = (h << 10) + (s << 6) + b;  //  hhhhhhssssiiiiii
        ***   findColorName() performs 3 functions.  First, it
        *** will auto-initialize itself if necessary.  Second,
        *** it will perform 3 sorts:
        ***   -3) byHSI:  sort by HSI and return first element of sorted list
        ***   -2) byNAME: sort by name and return first element of list
        ***   -1) byHEX:  (re)reads ntc.names, which is already sorted by HEX;
        ***               returns first element of list
        *** Third, on 0 or greater, will return the nth element of list
        *** Note: ntc.init() need not have been called.
        public colorName findColorName(int which)
         if (which < -3)  which = -3;
         if (which >= ntc.names.length)  which = ntc.names.length - 1;
         if (which == -1)  colorNames = null;     // free up for garbage collection
         if (colorNames == null)
         {   // (re)create list
             colorNames = new ArrayList<colorName>(ntc.names.length);
             for (int i = 0; i < ntc.names.length; i++)
                 colorNames.add(new colorName(ntc.names[1], ntc.names[0]));
            if (which == -1)  return(colorNames.get(0));
    }On compilation, I receive:
    D:\progming\java\ntc>javac colorName.java
    colorName.java:117: cannot find symbol
    symbol  : constructor colorName(java.lang.String[],java.lang.String[])
    location: class colorName
                    colorNames.add(new colorName(ntc.names[1], ntc.names[0]));
                                   ^
    1 errorLine 117 is the second-to-last executable line in code block. I know it is finding the ntc.names[][] array the ntc.class file. I had forgotten to compile ntc.java, and there were other errors, such as in line 115 where it couldn't find ntc.names.length. Compare camickr's two lines:
              List<Person> people = new ArrayList<Person>();
              people.add( new Person("Homer", 38) );As far as I can tell, I'm doing exactly the same thing. If you have any other feedback, feel free to make it. The full source may be found at:
    * http://r0k.us/rock/Junk/colorName.java
    PS1: I know I don't need the parenthesis in my return's. It's an old habit, and they look funny to me without them.
    PS2: My original design had the "static List<colorName> colorNames;" line defined within the findColorName() method. The compiler did not like that; it appears to be that one cannot have static variables within methods. Anyway, that's why I don't have separate sorting and getting methods. I'm learning; "static" does not mean, "keep this baby around". Its meaning is, "there is only one of these babies per class".
    -- Rich

  • Example of passing String Array from java to C using JNI

    hi all
    i searched net for passing string array from java to C but i dont get anything relevent
    i have
    class stu
    int rollno
    string name
    String [] sub
    i want to pass all as String array from java to C and access it C side

    1. Code it as though it were being passed to another method written in java.
    2. Redefine the method implementation to say "native".
    3. Run jnih to generate a C ".h" file. You will see that the string array
    is passed into C as a jobject, which can be cast to a JNI array.
    4. Write the C code to implement the method and meet the interface
    in the generated .h file.

  • Problems with string array, please help!

    I have a String array floor[][], it has 20 rows and columns
    After I do some statement to modify it, I print this array
    out in JTextArea, why the output be like this?
    null* null....
    null null...
    null null...
    How to correct it?

    a turtle graphics applet:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TG extends JApplet implements ActionListener {
      private int x, y;
      private int pendown, command, movement;
      String direction, output, temp;
      JLabel l1;
      JTextField tf1;
      JTextArea ta1;
      String floor[][] = new String[20][20];;
      public void init()
        x = 0;
        y = 0;
        pendown = 0;
        direction = "r";
        Container c = getContentPane();
        c.setLayout( new FlowLayout() );
           l1 = new JLabel( "Please type a command:" );
           c.add( l1 );
           tf1 = new JTextField(20);
           tf1.addActionListener( this );
           c.add( tf1 );
           ta1 = new JTextArea(20,20);
           ta1.setEditable( false );
           c.add( ta1 );
    public void actionPerformed( ActionEvent e )
           temp = tf1.getText();
           if( temp.length() > 1)
           command = Integer.parseInt(temp.substring(0,1));
           movement = Integer.parseInt(temp.substring(2,temp.length()));
           else
           command = Integer.parseInt(temp);
           switch(command)
                case 1:
                pendown=0;
                break;
                case 2:
                pendown=1;
                break;
                case 3:
                direct("r");
                break;
                case 4:
                direct("l");
                break;
                case 5:
               move(movement);           
                break;
                case 6:
                print();
                break;                                     
      public void direct(String s)
           if(direction == "r" && s =="r")
              direction = "d";
           else if(direction == "r" && s =="l")
              direction = "u";
           else if(direction == "l" && s =="r")
              direction = "u";
           else if(direction == "l" && s =="l")
              direction = "d";
           else if(direction == "u" && s =="r")
              direction = "r";
           else if(direction == "u" && s =="l")
              direction = "l";
           else if(direction == "d" && s =="r")
              direction = "l";
           else if(direction == "d" && s =="l")
              direction = "r";
      public void move(int movement)
           if(pendown == 1)
                if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "*";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "*";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "*";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "*";
            else if(pendown == 0)
                 if(direction == "u")
                for(int b=0;b<movement;b++)
                     floor[x][y+b] = "-";
                else if(direction == "d")
                for(int b=0;b<movement;b++)
                     floor[x][y-b] = "-";
                else if(direction == "l")
                for(int b=0;b<movement;b++)
                     floor[x-b][y] = "-";
                else if(direction == "r")
                for(int b=0;b<movement;b++)
                     floor[x+b][y] = "-";
          public void print()
         for(int row=0;row<20;row++)
           for( int column=0;column<20;column++)
                output += floor[row][column];
                if(column == 19)
                 output+="\n";
            ta1.setText(output);
    }

  • Problems with string arrays

    Previous task was:
    Write a class "QuestionAnalyser" which has a method "turnAnswerToScore". This method takes a String parameter and returns an int. The int returned depends upon the parameter:
    parameter score
    "A" 1
    "B" 2
    "C" 3
    other 0
    Alright, here's the recent task:
    Write another method "turnAnswersToScore". This method takes an array of Strings as a parameter, works out the numerical score for each array entry, and adds the scores up, returning the total.
    That's my code:
    class QuestionAnalyser{
    public static int Score;
    public String[] Answer;
    public static void main(String[] args) {}
         public int turnAnswerToScore(String[] Answer)
    for (int i = 0; i < Answer.length;i++) {
    if (Answer.equals("A")) {
    Score = Score + 1; }
    else if (Answer[i].equals("B")) {
    Score = Score + 2;}
    else if (Answer[i].equals("C")) {
    Score = Score + 3;}
    else {
    Score = Score + 0;}
    return Score;
    this is the error message I get:
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    QATest2.java:15: cannot resolve symbol
    symbol : method turnAnswersToScore (java.lang.String[])
    location: class QuestionAnalyser
    if(qa.turnAnswersToScore(task)!=total){
    ^
    What went wrong?
    Suggestions would be greatly appreciated!

    If I declare int score in the method i get this message
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ./QuestionAnalyser.java:20: variable score might not have been initialized
    score++; }
    ^
    ./QuestionAnalyser.java:23: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:27: variable score might not have been initialized
    score++;
    ^
    ./QuestionAnalyser.java:34: variable score might not have been initialized
    return score;
    ^
    4 errors
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    Exception in thread "main" java.lang.NoClassDefFoundError: QuestionAnalyser
         at QATest2.main(QATest2.java:4)
    This is the message I get from the submission page, but trying to compile it I get the same messages.
    The code looks like this, then
    class QuestionAnalyser{
    String[] answer;
    public static void main(String[] args) {}
         public int turnAnswersToScore(String[] answer)
    int score;
    for (int i = 0; i < answer.length; i++) {
    if (answer.equals("A")) {
    score++; }
    else if (answer[i].equals("B")) {
    score++;
    score++; }
    else if (answer[i].equals("C")) {
    score++;
    score++;
    score++; }
    else {}
    return score;
    When I leave 'public int score;' where it was before (right after the class declaration below the declaration of the string array) I get this but it compiles normally.
    The results of trying to compile your submission and run it against a set of test data was as follows:
    ----------Compilation output--------------------------------------
    javac QATest2.java
    ----------Sorry expected answer was-------------------------------
    The method turnAnswersToScore is working OK - well done!
    ----------Your answer however was---------------------------------
    wrong answer in turnAnswersToScore for
    BDCAADDCA
    Alright, even university students need to sleep :-)
    Good night.

  • Remove null values from string array

    Hi ,
    I have a string array in a jsp page which I save some values inside. After I store the values I want to print only those who are not null. How can I do this? Is there a way to delete the null values?

    Thank you but because I am new in programming what do you mean to use continue. Can you explain it a little bit further?<%
    //go through the array to check all the values
    for(int i=0; i<array.length();i++) {
    //If array is null, nothing happen
    if(array==null){
    //leave here blank; instead use continue like:
    //this will skip the statements next to it, and increments the value of i in for loop and continues to execute the body of for loop.
    //The same will be repeated till the last iteration.
    continue;
    //If array not null, then print value in a new line
    else{
    out.print(array+"<br>"); //don't change the logic here
    %>

  • Getting one character at a certain position from a string array

    Hi, i'm new at learning java, but have strong experience at C++ and asm. How would i get one character at a certain positon from a string array.
    for example:
    String Phrases[] = {"To be or not to be, that is the question","The Simpsons","The Mole","Terminator three rise of the machines","The matrix"};
    that is my string array above.
    lets say i wanted to get the first character from the first element of the array which is "T", how would i get this

    ok well that didn't work, but i found getChars function can do what i want. One problem, how do i check the contents of char array defined as char Inchar[];

  • How to add elements into java string array?

    I open a file and want to put the contents in a string array. I tried as below.
    String[] names;
    s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
    while (s.hasNext()) {
                    String item = s.next();
                    item.trim();
                    email = item;
                    names = email;
                }But I know that this is a wrong way of adding elements into my string array names []. How do I do it? Thanks.

    Actually you cannot increase the size of a String array. But you can create a temp array with the lengt = lengthofarray+1 and use arraycopy method to copy all elements to new array, then you can assign the value of string at the end of the temp array
    I would use this one:
    String [] sArray = null;
    s = new Scanner(new BufferedReader(new FileReader("outfile.txt")));
    while (s.hasNext()) {
        String item = s.next();
        item.trim();
        email = item;
        sArray = addToStringArray(sArray, email);
    * Method for increasing the size of a String Array with the given string.
    * Given string will be added at the end of the String array.
    * @param sArray String array to be increased. If null, an array will be returned with one element: String s
    * @param s String to be added to the end of the array. If null, sArray will be returned.(No change)
    * @return sArray increased with String s
    public String[] addToStringArray (String[] sArray, String s){
         if (sArray == null){
              if (s!= null){
                   String[] temp = {s};
                   return temp;
              }else{
                   return null;
         }else{
              if (s!= null){
                   String[] temp = new String[sArray.length+1];
                   System.arraycopy(sArray,0,temp,0,sArray.length);
                   temp[temp.length-1] = s;
                   return temp;
              }else{
                   return sArray;
    }Edited by: mimdalli on May 4, 2009 8:22 AM
    Edited by: mimdalli on May 4, 2009 8:26 AM
    Edited by: mimdalli on May 4, 2009 8:27 AM

Maybe you are looking for

  • Error -1426 : Solid Apple logo on Iphone after update

    Here's a new one. I went through and downloaded the 2.0 update about an hour ago. The update backed up the Iphone, then restored/updated it to 2.0. So far, so good! Then it got to the part where it looked like it was going to put back my own settings

  • Notifications failed to send mail for journal approval with attachments

    Issue : Notifications failed to send mail for journals sent for approvals with attachments. Error : [WF_ERROR] ERROR_MESSAGE=3835: Error '-6502 - ORA-06502: PL/SQL: numeric or value error: character string buffer too small' encountered during executi

  • Pb not connecting to app world on pc

    when i tried to download an app to my playbook through pc app world a dialog box appears on computer screen saying "your playbook is secured with a password please enter the password to connect" but password protection is disabled in my device pls he

  • Error Me683

    Hi, One of my client is facing a problem very frequently.He creates a PO with 100 to 150 items from the Purchase requisitions once he completes the PO the user saves and he could see the PO number.then after words when he try to see the PO he gets th

  • Need help with openDialog

    In the Photoshop script I'm writing, I ask the user to open a file using:      open(File(openDialog())); That works fine. But the user will always be opening an Illustrator (.ai) file. Normally that brings up a dialog box called "Import PDF". But tha