Putting a string in a char array?

Is it possible for the following string 'key' to be placed in array without having to manually go through the charAt methods?
String key = "ABCDEFGH";
char[] columnNames = {
key.charAt(0), key.charAt(1), key.charAt(2),key.charAt(3),key.charAt(4),key.charAt(5),key.charAt(6),key.charAt(7),
};

I'm still unclear on what you're trying to do. However, I can replace your big charAt() array mess above with the following code:public class ChatAtTest
    public static void main (String[] args)
        String s = "Hello this is not an eleven-char sentence!xxxxxx";
        if (s.length() <= 0 || s.length() % 8 != 0)
            System.err.println("["+s+"] must be a multiple of 8 characters");
            System.exit(8);
        int numRows = s.length()/8;
        char[][] charRows = new char[numRows][];
        for (int i=0; i<numRows; i++)
            String sub = s.substring(i*8, (i*8)+7);
            charRows[i] = sub.toCharArray();
        for (int row = 0; row < charRows.length; row++)
            System.out.print("ROW "+row+"\t : ");
            for (int aChar = 0; aChar<charRows[row].length; aChar++)
                System.out.print(charRows[row][aChar]+" ");
            System.out.println();
}you end up with the following output:ROW 0      : H e l l o   t
ROW 1      : i s   i s   n
ROW 2      : t   a n   e l
ROW 3      : v e n - c h a
ROW 4      :   s e n t e n
ROW 5      : e ! x x x x x Is that what you're looking for?
Grant

Similar Messages

  • How to put a String into a byte array

    How can i put a String into a byte array byte[]. So that i can send it to the serial port for output to an LCD display. Cheers David

    javadocs for String
    getBytes
    public byte[] getBytes()
    Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
    Returns:
    The resultant byte arraySince:
    JDK1.1

  • How can I cast a String to a char array?

    My code is:
    char []sender = new char[48];
    String senderStr = "event_router_send";
    sender=senderStr.toCharArray();The sender array's size will be changed to the String senderStr's length. Is there a better way to fill a array from a String object and keep the array's size.

    youhaodiyi wrote:
    My code is:
    char []sender = new char[48];
    String senderStr = "event_router_send";
    sender=senderStr.toCharArray();The sender array's size will be changed to the String senderStr's length. Is there a better way to fill a array from a String object and keep the array's size.Here's how:
    int index = 0;
    for(char c: senderStr.toCharArray()) {
        sender[index++] = c;
    }But why do you want to keep the array size in tact? What if the String has more characters in it than the array's size?

  • Help:How to get a java String value from a C char array?

    Hi,everyone,could you help me?
    the following is a C struct that i want to recieve a short message:
    struct MO_msg{
    unsigned long long msgID;          //Message ID
    char      dest_id[21]; //Destination Mobile Phone Number
    char      service_id[10];     //
    Now I want to put the "dest_id " value of this struct into a Java String variable.But I dont know how to implement it!
    The following is a block of source code that i implement this functions.But it cant get a String value ,and throw out a Exception:
    java.lang.NullPointerException
    at java.lang.StringBuffer.append(StringBuffer.java:389)
    JNIEXPORT jint JNICALL Java_md_EMAP_thread_RubeMOTSSX_getMO
    (JNIEnv * env, jobject obj, jint connId, jobject mo){
         struct MO_msg MO;
         tssx_cmpp_api_debug_flag = 1;
         int result = CMPP_Get_MO((int)connId,&MO);
         if (result == 0){
              jclass cls = (*env)->GetObjectClass(env,mo);
              jfieldID msgId = (*env)->GetFieldID(env,cls,"msgId","J");
              jfieldID dest_Id = (*env)->GetFieldID(env,cls,"dest_Id","Ljava/lang/String;");
              jfieldID serviceId = (*env)->GetFieldID(env,cls,"serviceId","Ljava/lang/String;");          
              (*env)->SetLongField(env,mo,msgId,MO.msgID);               
              (*env)->SetCharField(env,mo,dest_Id,*destId);
              (*env)->SetCharField(env,mo,serviceId,MO.service_id);
         return result;
    Please help me!Thanks!

    bschauwe:Thank you for your help!
    Yes,just as you say,using NewString Or NewStringUTF can import a C char array into a Java String variable! But now I have another question,when i use these two functions ,i found that it cant deal with Chinese character!
    do you have such experiences to deal with another language charset?if you have ,can you tell me how to deal with it.

  • How to convert char array to string

    sirs,
    i have written a method in java which will return a randomly generated string of a fixed length. i am creating one one character and inserting it into char array.
    at last i am converting it to string
    like this
    String newpass= pass.toString();// pass is a char array
    but problem is that the string is having different value what i hav generated.
    if i am doing like this..
    String newpass= new String(pass);// pass is a char array
    here newpass is having correct value but having some error
    error in the sense when i print
    System.out.println(newpass+"some text");
    "some text" is not printing
    can you suggest the better way

    /*this is my method */
    private String generateString(int len){
              char pass[] = new char[10];
              int cnt=0;
              int temp=0;
              Random randomGenerator = new Random();
                   for (int idx = 0; idx < 1000; ++idx)
                        temp = randomGenerator.nextInt(1000)%128;
                   if((temp>=65 && temp<=90)||(temp>=97 && temp<=122)||(temp>=48 && temp<=57))
                             pass[cnt]=(char)temp;
                             cnt++;               
                        if(cnt>=len) break;
                   String newpass= pass.toString();
                   String newpass1= new String(pass);
                   System.out.println("passed pass"+newpass+"as"+newpass1+"sa");
              return newpass;
    here newpass and newpass1 are having separate values
    why ??
    Edited by: Shovan on Jun 4, 2008 2:21 AM

  • Char array conversion from String: toCharArray()

    Greetings,
    Can anyone tell me why this code:
    import com.wuw.debug.Trace;
    public
    class charTest
       public static void
       main( String[] args )
           String strIn = new String( "strIn" );
           Trace.DTRACE( "strIn: "+strIn );
           Trace.DTRACE( "strOut: "+strIn.toCharArray() );
    }produces this output:
    [DTRACE]: strIn: strIn
    [DTRACE]: strOut: [C@1fef6f
    and not:
    [DTRACE]: strIn: strIn
    [DTRACE]: strOut: strIn

    Because:
    String.toCharArray returns an array of chars.
    An array is basically an object in java.
    Objects are converted to strings with the method toString - if it's not implemented in your class the string that method returns will be of the form classname@hashcode.
    In the case of a char array, the name of the class is "[C". The hashcode of you object seems to be "1fef6f" (in hex).
    You'll just have to remember that an array of chars is [i]not a string in java.

  • Importing text file into 2D char array

    Hey folks. I've aged a few years trying to figure this project out. Im trying to make a crossword puzzle and am having problems importing the answer letters into a 2D array of 15*15. The text file would look something like this:
    LAPSE TAP RAH
    AVAIL OLE ODE
    BARGE PARADOX
    etc
    I have JTextFields that the user will answer and a button the user can press to see if the answers are right by comparing the 2D array answer with what the user inputted.-the user input would be scanned and put into a 2D array also.
    How should i go about inserting each letter into an array? The spaces i would later need to make code to grey out the text field. This is what i have so far. Forgive me if its sloppy.
         class gridPanel extends JPanel
              //----Setting Grid variables
              private static final int ROWS = 15;
              private static final int COLS = 15;
              String[] letters = { "A", "B", "C", "D", "E" };// To test entering strings into array
               gridPanel()
                 this.setBackground(Color.BLUE);
                 //.......Making my JTextField grid for user input
                 JTextField[][] grid = new JTextField[ROWS][COLS];
                 for(int ROWS = 0; ROWS<grid.length; ROWS++)
                     for(int COLS = 0; COLS<grid.length; COLS++)
                         grid[ROWS][COLS] = new JTextField(1);
                         add(grid[ROWS][COLS]);
                     //grid[ROWS][COLS].setText("" + letters[0]);
                 String an = null;
                 StringTokenizer tokenizer = null;
                 Character[][] answer = new Character[ROWS][COLS];
              try{
                 BufferedReader bufAns = new BufferedReader( new FileReader("C:\\xwordanswers.txt"));
                 for (int rowCurrent = 0; rowCurrent < ROWS; rowCurrent++)
              an = bufAns.readLine();
              tokenizer = new StringTokenizer(an);
              for (int colCurrent = 0; colCurrent < COLS; colCurrent++) {
              char currentValue = tokenizer.nextToken().charAt(0);//Needs to be changed to reflect each letter
                        answer[rowCurrent][colCurrent] = currentValue;
                    System.out.println(currentValue);
              }catch (IOException ioex)           
                        System.err.println(ioex);
                        System.exit(1);
            }//xword graphics end
          This obviously prints the first char of each word, it also gives me an "Exception in thread "main" java.util.NoSuchElementException" error for some reason.
    Any help is greatly appreciated.
    John

    If the file format is stored as follows:
    APPLE
    L A
    PARSE
    N E
    PEAR then we can parse this into a 2D char array:
    char[][] readMap(String fileName) {
        char[][] ret = new char[ROWS][COLS];
        FileInputStream FIS = new FIleInputStream(fileName);
        int i, j;
        for(i = 0; i < ROWS; i++)
            for(j = 0; j < COLS; j++)
                ret[i][j] = FIS.read();
        FIS.close();
        return ret;
    }Then you can use the resulting 2D char array in your answer checking mechanism.
    Hope this helps~
    Alex Lam S.L.

  • How to improve the speed of creating multiple strings from a char[]?

    Hi,
    I have a char[] and I want to create multiple Strings from the contents of this char[] at various offsets and of various lengths, without having to reallocate memory (my char[] is several tens of megabytes large). And the following function (from java/lang/String.java) would be perfect apart from the fact that it was designed so that only package-private classes may benefit from the speed improvements it offers:
        // Package private constructor which shares value array for speed.
        String(int offset, int count, char value[]) {
         this.value = value;
         this.offset = offset;
         this.count = count;
        }My first thought was to override the String class. But java.lang.String is final, so no good there. Plus it was a really bad idea to start with.
    My second thought was to make a java.lang.FastString which would then be package private, and could access the string's constructor, create a new string and then return it (thought I was real clever here) but no, apparently you cannot create a class within the package java.lang. Some sort of security issue.
    I am just wondering first if there is an easy way of forcing the compiler to obey me, or forcing it to allow me to access a package private constructer from outside the package. Either that, or some sort of security overrider, somehow.

    My laptop can create and garbage collect 10,000,000 Strings per second from char[] "hello world". That creates about 200 MB of strings per second (char = 2B). Test program below.
    A char[] "tens of megabytes large" shouldn't take too large a fraction of a second to convert to a bunch of Strings. Except, say, if the computer is memory-starved and swapping to disk. What kind of times do you get? Is it at all possible that there is something else slowing things down?
    using (literally) millions of charAt()'s would be
    suicide (code-wise) for me and my program."java -server" gives me 600,000,000 charAt()'s per second (actually more, but I put in some addition to prevent Hotspot from optimizing everything away). Test program below. A million calls would be 1.7 milliseconds. Using char[n] instead of charAt(n) is faster by a factor of less than 2. Are you sure millions of charAt()'s is a huge problem?
    public class t1
        public static void main(String args[])
         char hello[] = "hello world".toCharArray();
         for (int n = 0; n < 10; n++) {
             long start = System.currentTimeMillis();
             for (int m = 0; m < 1000 * 1000; m++) {
              String s1 = new String(hello);
              String s2 = new String(hello);
              String s3 = new String(hello);
              String s4 = new String(hello);
              String s5 = new String(hello);
             long end = System.currentTimeMillis();
             System.out.println("time " + (end - start) + " ms");
    public class t2
        static int global;
        public static void main(String args[])
         String hello = "hello world";
         for (int n = 0; n < 10; n++) {
             long start = System.currentTimeMillis();
             for (int m = 0; m < 10 * 1000 * 1000; m++) {
              global +=
                  hello.charAt(0) + hello.charAt(1) + hello.charAt(2) +
                  hello.charAt(3) + hello.charAt(4) + hello.charAt(5) +
                  hello.charAt(6) + hello.charAt(7) + hello.charAt(8) +
                  hello.charAt(9);
              global +=
                  hello.charAt(0) + hello.charAt(1) + hello.charAt(2) +
                  hello.charAt(3) + hello.charAt(4) + hello.charAt(5) +
                  hello.charAt(6) + hello.charAt(7) + hello.charAt(8) +
                  hello.charAt(9);
             long end = System.currentTimeMillis();
             System.out.println("time " + (end - start) + " ms");
    }

  • Reading .txt file into char array, file not found error. (Basic IO)

    Iv been having some trouble with reading characters from a text file into a char array. I havnt been learning io for very long but i think im getting the hang of it. Reading and writing raw bytes
    and things like that. But i wanted to try using java.io.FileReader to read characters for a change and im having problems with file not found errors. here is the code.
    try
    File theFile = new File("Mr.DocumentReadMe.txt");
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);
    char buffer[] = new char[(int)theFile.length()];
    int readData = 0;
    while(readData != -1)
    readData = readMe.read(buffer);
    jEditorPane1.setText(String.valueOf(buffer));
    catch(Exception e)
    JOptionPane.showMessageDialog(null, e,
    "Error!", JOptionPane.ERROR_MESSAGE);
    The error is: java.io.FileNotFoundException: C:\Users\Kaylan\Documents\NetBeansProjects\Mr.Document\dist\Mr.DocumentReadMe.txt (The system cannot find the file specified)
    The text file is saved in the projects dist folder. I have tried saving it elsewhere and get the same error with a different pathname.
    I can use JFileChooser to get a file and read it into a char array with no problem, why doesnt it work when i specify the path manually in the code?

    Well the file clearly isn't there. Maybe it has a .txt.txt extensionthat Windows is kindly hiding from you - check its Properties.
    But:
    String path = theFile.getCanonicalPath();
    FileReader readMe = new FileReader(path);You don't need all that. Just:
    FileReader readMe = new FileReader(theFile);And:
    char buffer[] = new char[(int)theFile.length()];You don't need a buffer the size of the file, this is bad practice. Use 8192 or whatever.
    while(readData != -1)
    readData = readMe.read(buffer);
    }That doesn't make sense. Read the data into the buffer and repeat until you get EOF? and do nothing with the contents of the buffer? The canonical read loop in Java goes like this:
    while ((count = in.read(buffer)) > 0)
      out.write(buffer, 0, count); // or do something else with buffer[0..count-1].
    jEditorPane1.setText(String.valueOf(buffer));Bzzt. That won't give you the content of 'buffer'. Use new String(buffer, 0, count) at least.

  • Is it possible to put different movieclips in the same array?

    Hello. I have two different bullet movieclips. I would like to put them both into one bullet array, but it seems that all instances of the second movieclip are not controlled by bullet_ary[i]

    then you have an incorrect reference (eg, you are using a non-string and the movieclip doesn't exist when the array is defined) or are using the array incorrectly.
    for more specific help, copy and paste your array and show how you're trying to reference the problematic moveiclip.

  • Char arrays, spliting

    am new to java programing.
    am trying to write a simple hangman game, that asks a user to pick a topic and then takes the elements in that topic i.e. elements in an array an picks one at random, everything up to this point works well. When i try to split the choosen word up and store it in a char array i get and error message:
    incompatible types - found java.lang.string[] but expected char
    the code is:
    private void FillArray1()
    words[0] = "elephant";
    words[1] = "cat";
    words[2] = "dog";
    words[3] = "horse";
    words[4] = "sheep";
    choice = GenRandom();
    Split();
    public void Split()
    for (int i=0; i < hidden.length; i++){
    hidden[i] = choice.split ("");}
    private String GenRandom()
    randGen = new Random();
    int index = randGen.nextInt(words.length);
    return words[index];
    does anyone know wot am doing wrong. its being written in an enviroment called bluej.

    If you want to convert a String to an array of chars do:
    String s = "test";
    char[] charArray = s.toCharArray();And I think you mean:
    private String[] words; // and not  private string[] words;

  • Is there only one way to initialize a char array ?

    char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
    why does't this working like it works in c ?
    char hey[]={"you are dead !"};
    ??

    DogsAreBarking wrote:
    char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
    why does't this working like it works in c ?
    char hey[]={"you are dead !"};
    ??C != Java
    In C, strings are char arrays, in Java they are instances of java.lang.String.
    edit: try this:
    char[] chars = "hello, world".toCharArray();

  • Splitting a String to a Character array

    I need to split a string to a character array. All I can find is how to split on spaces, etc.
    Can you help me?
    Thanks
    Ozmodiar

    myString = myString.toCharArray();Type mismatch! You cannot convert String myString to
    char[].
    Head loss - sorry, not switched on today ...
    char []mychars = myString.toCharArray();

  • HELP WITH CHAR ARRAY

    Here is the go folks this is a pice of code which I was helped with by a member of this forum, THANX HEAPS DUDE. What has happened now is the criteria is changed, previously it would search for a string in the vector. But now I have to have searches with wildcards, so it needs to utilize a char array methinks. So it will go through change the parameter to a char array, then go through the getDirector() method to return a director string, then it needs to loop through the char array and check if the letters are the same. then exit on the wild card. Now all this needs to be happening while this contruct down the bottom is looping through all the different elements in the moviesVector :s if anyone could give me a hand it is verry welcome. I must say also that this forum is very well run. 5 stars
    public void searchMovies(java.lang.String searchTerm) {
    Iterator i = moviesVector.iterator();
    while (i.hasNext()) {
    Movie thisMovie = (Movie)i.next();
    //Now do what you want with thisMovie. for instanse:
    if (thisMovie.getDirector().equals(searchTerm))
    foundMovies.add(thisMovie);
    //assumes foundMovies is some collection that we will
    //return later... or if you just want one movie, you can:
    //return thisMovie; right here.
    }

    Sorry, I clicked submit, but i didnt enable to wtch it, so i stoped it before it had sent fully. Evidently that didnt work.

  • Converting a String to a char

    Hello,
    How to a convert a String object consisting of a single character to a char type. I.e., suppose I have
    String myStr = "a"
    I want to be able to convert myStr to a char for use in a switch case statement. Thanks.
    CoreDummy

    i know I can just convert the String "a" to a char array...but there should be a better way to do this...
    Forever an idiot,
    CoreDumb

Maybe you are looking for

  • When I try to open a .pdf file my computer just opens "new tabs" one after another

    I have downloaded Adobe Reader in order to view .pdf files. When I double click on the file name, typically as an attachment to an email a repeated flow of "new tab(s)2 is generated and just goes on it seems for ever. The only way out I can find is t

  • GPS maps on 8820 for Ukraine

    Hello! Where could I get the GPS maps for Ukraine? I see that maps for South America are very detalized since Kyiv is marked only as a dot. Please help me to obtain that maps. Thank you! WBR, Roman V. Sytnik

  • S510p s59-383309 extremely dim, dark video quality of integerate​d webcam

    please help, got this new laptop just 2 days before, the quality of the laptop  is pathetic ! the drivers do not properly get install, when i click the setup, the setup starts, it extracts the files, but after granting the admin permission, the the 

  • Convenience Key on my Torch does not work

    Hi Everyone! Seek your help as the convenience key on my torch does not work. I have changed the setting as well but to no avail. Regards - Nitin Solved! Go to Solution.

  • PhotoBooth Replaces Managed Account Picture w/o Admin OK

    Hi, the Photo Booth that comes with the OS is letting students replace the account photo where the account is managed. This is what I did. 1. Open Photo Booth and took a picture. 2. Clicked on the picture and then clicked on Account Picture. 3. It th