Creating String frm new String(charBuffer.array()) Vs charBuffer.toString()

Whats the difference in creating String from CharBuffer by using array and by using toString() ?
When ever i have some UTF-8 chars in my file (""someFile"), String created from new String( charBuffer.array()) appends some extra null/junk charaters at the very end of the file.
How ever when i try charBuffer.toString() its working fine.
For simple ASCII i.e ISO-*** charset both methods are working fine.
Please see below code for reproducing. Here "someFile" is any text file with some UTF-8 characters.
public char[] getCharArray()
throws IOException
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
FileInputStream fis = new FileInputStream("someFile");
FileChannel channel = fis.getChannel();
int size = (int) channel.size();
MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0 , size);
CharBuffer cb = decoder.decode(mbb);
channel.close();
fis.close();
return cb.array();
public String getAsString()
throws IOException
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
FileInputStream fis = new FileInputStream("someFile");
FileChannel channel = fis.getChannel();
int size = (int) channel.size();
MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0 , size);
CharBuffer cb = decoder.decode(mbb);
channel.close();
fis.close();
return cb.toString();
String fromToString = getAsString();
String fromCharArray = new String(getCharArray());

Whats the difference in creating String from CharBuffer by using array and by using toString() ?array() returns the entire backing array regardless of offset and position. toString() takes those into account.
When ever i have some UTF-8 chars in my file (""someFile"), String created from new String( charBuffer.array()) appends some extra null/junk charaters at the very end of the file.More probably you haven't filled the array.
How ever when i try charBuffer.toString() its working fine.So there you go.

Similar Messages

  • "String str=new String("My String")" v.s. "String str="My String";

    -- what's the difference bet String str="My String"; to this
    String str=new String("My String");

    Its a subtle one. Its also been asked a hundred times before :-)
    When a java class is compiled it "interns" all the Strings it can find.
    Anywhere that you use that string, gets replaced with a reference to that string.
    So the first gets a reference to the interned String.
    The second creates a new String, using the interned String as an argument - results in reserving new memory.
    Take this code:
    String str1 = "My String";
    String str2 = "My String";
    String str3=  new String("My String");In effect the compiler turns it into something like this:
    String internedString = "My String"
    String str1 = internedString;
    String str2 = internedString;
    String str3 = new String(internedString);So initially, it only stores "MyString" once, and all your String variables point at that same memory space. As Strings are immutable in java (the contents never change) this is safe to do. str3 creates a NEW String, which reserves new memory, and copies the contents of internedString into it.
    So
    str1 == str2 (they point to the same bit of memory)
    str1 != str3 (str3 created a new String, so is in new memory)
    str1.equals(str3) (the contents of the strings are the same)
    Hope this helps,
    evnafets

  • String name = new String {...} what is this?

    Hi,
    Java beginner, moving from C++:
    protected String[] name = new String[] {
              Integer.toString(1),
    Integer.toString(2)
         };what does a bracket mean after new String[] ?
    Thanks,

    Thanks, I didn't know what to search for in
    google...
    Is it generalizable to any object?Why don't you try it with various objects and primitives? Then you'll find out for yourself.
    You can also read the JLS
    http://java.sun.com/docs/books/jls/second_edition/html/j.title.doc.html
    or
    http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html
    Or any of a number of books or tutorials. This is basic stuff. It should be covered.
    Sun's basic Java tutorial
    Sun's New To Java Center. Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    http://javaalmanac.com. A couple dozen code examples that supplement The Java Developers Almanac.
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's Thinking in Java (Available online.)
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java.

  • Which is better and why a = new String("AA") or a = "AA"

    Hi,
    Which is better and why
    String a = new String("AA") or
    String a = "AA"
    Does invoking a construtor waste memory? Please explain in detail.
    Thanks in advance
    Deepak

    > So in case "AA" not there in string pool,
    That is not correct.
    does new creates "AA" on string pool as well as heap memory?Yes. The literal "AA" points to a pooled String object. The new operator creates a new String object with the same character sequence ("AA"). You can verify this with a little code...
    String s = new String("AA");
    assert s != "AA";
    assert s.equals("AA");
    assert s.intern() == "AA";~

  • Difference between str="Hai"; and str = new String("Hai");

    HI,
    String szFirst = "Hello World":
    String szSecond = new String("Hello World");What is the difference between the two types of string initialization?

    RajivGuna wrote:
    HI,
    String szFirst = "Hello World":
    String szSecond = new String("Hello World");What is the difference between the two types of string initialization?What do you think the difference is?

  • String object vs String literal

    Hi ,
    I understand how the string objects are created using new operator and using literal.I also understand how they are stored in memory.All I want to know is that when and why should I create a String object using new and when I should create an object using literal.Is there any specific reason for creating an object using new operator when objects created by both the ways are immutable.
    Thanks for the help in advance.
    Thanks
    Mouli

    If you look at the String source code (particularly the constructors) youll learn a lot.
    String objects contain a char[] array - and this is the most important part --> a start and length value.
    I believe they were attempting to optimize, but this has important implications for developers.
    String objects dont necessarily store just the text you see, it may just reference a much bigger char array.
    For example, say an API passes you a string that is (lets pretend) a file path (C:\files\java\...\file.txt) that is 1,000,000 characters long.
    Now say that you call getFileName() and want to save the filename in a list.
    String filename = API.getFile("...").getFileName();
    List.add(filename);
    Say you do this about 250,000 times.
    You estimate that the average file name is 10 chars and ensure there is that much RAM.
    You run out of memory. Why?
    Well, this example actually happened to me in a real program I was writing to archive drive files.
    File.getFilename() returns a substring() of the entire File path.
    However, substring is implemented to return a String that just references the original char[] array!
    So the really long file path never gets garbage collected!
    I was able to fix the program by coding it:
    String filename = new String(API.getFile("...").getFileName()); // Copies only the needed chars!
    List.add(filename);
    So thats really all you need to watch out for. If memory is a concern in your program you want to
    make sure you arent referencing large char[] arrays unnecessarily.
    But like all things, this is rarely anything to give much thought to.
    Only something to remember if you run into problems after coding sensibly and profiling
    (or in my case, crashing with OOM exceptions, lol).

  • Create Files in new directory

    Hi can create files using the code shown in the current working directory of my executable when this.filePath = "atext.xml". But if I change this.filePath ="c:\data\atext.xml" I get an error such as "System cannot find the path specified" true, the path hs not been created, but that is what I am trying to do. What do I need to change.?
    try{
    String fileName = new String();
    fileName = this.filePath;
    FileWriter fw = new FileWriter(fileName);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter outFile = new PrintWriter(bw);
    outFile.println(emptyXML);
    outFile.close();
    catch (IOException ioex){
    System.out.println(ioex.getMessage());
    System.exit(1);

    Probably the message means that the c:\data directory doesn't exist. You can't create a file in a nonexistent directory, so you would have to create the directory first for that to work.

  • JSP String != JavaScript String

    I've run across a problem that has intrigued me. Consider the following:
    <% String test = new String();
    test = "Hello Mr. Anderson...";
    %>
    <script language="javascript">
    function doThis() {
    alert("TEST: " + "<%=test%>");
    </script>
    // No problem, will work just fine. Now add an escape sequence (\n)
    // to the test string
    <% String test = new String();
    test = "Hello Mr. Anderson...\n";
    %>
    <script language="javascript">
    function doThis() {
    alert("TEST: " + "<%=test%>");
    </script>
    Now we get
    error: Unterminated string constant
    on any call to doThis(). Why????? Javascript has wrappers around it's primitive data types as well, so I was thinking the conversion should be smooth here. Any experts out there know what's happening here?
    Thanks,
    Chris

    The reason is you are printing out what's in the Java string to the browser, and that results in this:
    "Hello Mr. Anderson...
    So, as the first responder said, you need to escape the \n with \\n, which will write:
    "Hello Mr. Anderson...\n"
    in the browser, which will get translated in the Javascript parser as a new line.

  • Creating new String using only specific set of chars from another String

    I've performance troubles doing this task:
    I have a very long String A (up to 1 million character length)
    This String contains different characters.
    I need to create a String B containing only specific characthers (with a defined character code)
    An example:
    String A: [80]='P' [65]='A' [71]='G' [69]='E'For example I want to extract only character 65 and 71
    String B: [65]='A' [71]='G'I already did the code to do this, (it's quite simple) but I think I have some very big performance issues, and I suppose I can do this task much more quickly!!
    String out = "";
              for (counter = 0; counter < text.length(); counter++) {
                   char currentchar = text.charAt(counter);
                   int currentvalue = (new Integer(currentchar)).intValue();
                   switch (currentvalue) {
                   case 65:
                        char[] newstring = new char[1];
                        newstring[0] = currentchar;
                        out += new String(newstring);
                        break;
                   case 71: //
                        break;
                   // other cases
                   default:
                        // nothing to do...
              }Can you suggest me something to improve the performances?
    Thank you!

    If you've got a number of characters in your acceptance set I'd use indexOf, and I'd probably use StringCharacterIterator. Mind you, with a million characters I'd probably not load them all at once anyway, but process them as streams.
    StringBuffer out = new StringBuffer(s.length() / 5); // allocate plenty
    StringCharacterIterator it = new StringCharacterIterator(s);
    for(char c = it.first(); c != CharacterIterator.DONE; c = it.next())
      if("AG".indexOf(c) >= 0)
          out.append(c);
    return c.toString();

  • Easy way to create a list of strings in an object?

    I'm trying to create a HashSet of Strings but I don't want to have to add each string to the HashSet. There is a constructor for HashSet that allows you to give it a Collection. But how can I create a Collection of String other than having to add each string? Can I just :
    HashSet hs = new HashSet("String1", "String2", "String3", "String4");
    ?

    This programming problem is as old as the hills, and there are a zillion ways to do it. One of the simplest is by using String.split. Example:   String separator = "[^\\w]+";
       String string = "I think, therefore I am; or maybe not. What do you think?";
       String[] array = string.split(separator);
       System.out.println("String    : \"" + string + "\"");
       System.out.println("Word count: " + array.length + " words.");The key is the String separator. This is what is known as a "regular expression." It looks pretty obtuse (and is); do some research on regular expressions to figure out it means.
    This example does not account for a few special cases, such as words split between lines with hyphens, and perhaps words enclosed in double quotes. That is left as an exercise for the reader.

  • Why are date and time strings lost when indexing an array in a for loop

    Hi, 
    I have an application where i'm reformatting data from a spreadsheet for graphical display on a LabVIEW dashboard.
    the original spreadsheet has date and time values in separate columns, and i'm merging them and converting to a timestamp value.  But something's not working.  Does anyone know why the string value is lost when the array indexes into this for loop?
    Attachments:
    failed array index.png ‏142 KB

    Can you attach your VI with some typical values? (e.g. create in indicator on the 2D array, run your VI, then turn the indicator (now containing data) into a diagram constant). Place the FOR loop related code and that diagram constant into a new VI and attach it here.
    How many times does the FOR loop run? Could it be that the last element of each 1D array is an empty string? (unless you put a wait inside the FOR loop, you'll never see the other elements in the probe)
    LabVIEW Champion . Do more with less code and in less time .

  • New String(byte[]) taking up huge space?

    Ok. I have a byte[] of approx. 5.000.000 bytes. Whenever, at any point, I try to create a String using this array by new String(array), my memoryusage increases by about 60/65 megabytes. Can anyone please explain me why on earth it's doing this?
    Note also that this space is not freed up by the GC (afterwards).
    Thanks in advance

    Actually, I've discovered some details about the swing textcomponents. They're very bad for 'simply' showing 2mb+ files.
    Check out these bugs; original and "more recent".
    It doesn't quite explain why putting a byte array to a string occupies twice the space, but it does seem to account for the huge memory increase when putting it to a JTextArea.
    String is immutable so it has to copy your char[] to
    a new char[] backing the String. If it used theSure thing, but I'm passing on a byte[] array, and afaik, it's not using this array and should only copy it. Once.
    Oh hey, could it be that the bytes are saved in unicode? That would double the size... and make sense...
    Oh and PS; Maybe you should read this if you really think strings are immutable... (although you are generally correct :))

  • PL/SQL function to read a string of characters into an array

    I was wondering if there is an easier way than using the substr function multiple times. Here is the example:
    Suppose you have a varchar2 variable that contains the word 'Apple'. The function should take it and produce an array. We would invoke it like this:
    <what data structure?> a := stringunpackerfunction(x);
    // x is the varchar2 containing 'Apple'.
    The resulting a would be such that a[0] is 'A', a[1] is 'p', a[2] is 'p', a[3] is 'l' and a[4] is 'e'.
    If there is no direct function to do this in a single invocation, is there a function to simply read a string of characters and return 'the next character'?
    Thanks,
    Regards,
    Srini

    There is a procedure out there called PS_PARSE which takes a string and converts to an array provided with an identified separator. Works for us pretty well.
    I just grabbed this off of google. I am presuming this should work fine. It has been sometime since we implemented ours that I forget if there were any additional modifications that we made. I think there was one regarding the size of the string that could be handled. I forget precisely. Anyways... take a peek at it. Its makes things easy in that your logic is pretty streamlined.
    Barry C
    http://www.myoracleportal.com
    create or replace PACKAGE PS_Parse
    IS
         || PL/SQL table structures to hold atomics retrieved by parse_string.
         || This includes the table type definition, a table (though you can
         || declare your own as well, and an empty table, which you can use
         || to clear out your table which contains atomics.
         TYPE atoms_tabtype IS TABLE OF VARCHAR2(60) INDEX BY BINARY_INTEGER;
         atoms_table atoms_tabtype;
         empty_atoms_table atoms_tabtype;
         || The standard list of delimiters. You can over-ride these with
         || your own list when you call the procedures and functions below.
         || This list is a pretty standard set of delimiters, though.
         std_delimiters VARCHAR2 (50) := ' !@#$%^&*()-_=+\|`~{{]};:''",<.>/?';
         /* Display contents of table using DBMS_OUTPUT */
         PROCEDURE display_atomics
              (table_in IN atoms_tabtype, num_rows_in IN NUMBER);
         || The parse_string procedure: I provide two, overloaded definitions.
         || The first version puts all atomics into a PL/SQL table and would
         || be used in a PL/SQL Version 2 environment. The second version places
         || all atomics into a string, separating each atomic by a vertical bar.
         || (My code does NOT do any special handling when it finds a "|" in
         || the string. You have to deal with that when you extract the atomics.
         ||
         || See the program definition for more details on other parameters.
         PROCEDURE parse_string
              (string_in IN VARCHAR2,
              atomics_list_out OUT atoms_tabtype,
              num_atomics_out IN OUT NUMBER,
              delimiters_in IN VARCHAR2 := std_delimiters);
         PROCEDURE parse_string
              (string_in IN VARCHAR2,
              atomics_list_out IN OUT VARCHAR2,
              num_atomics_out IN OUT NUMBER,
              delimiters_in IN VARCHAR2 := std_delimiters);
         /* Count the number of atomics in a string */
         FUNCTION number_of_atomics
              (string_in IN VARCHAR2,
              count_type_in IN VARCHAR2 := 'ALL',
              delimiters_in IN VARCHAR2 := std_delimiters)
         RETURN INTEGER;
         /* Return the Nth atomic in the string */
         FUNCTION nth_atomic
              (string_in IN VARCHAR2,
              nth_in IN NUMBER,
              count_type_in IN VARCHAR2 := 'ALL',
              delimiters_in IN VARCHAR2 := std_delimiters)
         RETURN VARCHAR2;
    END PS_Parse;
    create or replace PACKAGE BODY PS_Parse
    IS
    /* Package variables used repeatedly throughout the body. */
    len_string     NUMBER;
    start_loc     NUMBER;
    next_loc     NUMBER;     
    || Since the PUT_LINE procedure regards a string of one or more
    || spaces as NULL, it will not display a space, which is in
    || PS_Parse a valid atomic. So I save a_blank in the PL/SQL
    || table instead of the space itself.
    a_blank CONSTANT VARCHAR2(3) := '" "';
    /*--------------------- Private Modules ---------------------------
    || The following functions are available only to other modules in
    || package. No user of PS_Parse can see or use these functions.
    FUNCTION a_delimiter
    (character_in IN VARCHAR2,
    delimiters_in IN VARCHAR2 := std_delimiters)
    RETURN BOOLEAN
    || Returns TRUE if the character passsed into the function is found
    || in the list of delimiters.
    IS
    BEGIN
    RETURN INSTR (delimiters_in, character_in) > 0;
    END;
    FUNCTION string_length (string_in IN VARCHAR2)
    RETURN INTEGER
    IS
    BEGIN
    RETURN LENGTH (LTRIM (RTRIM (string_in)));
    END;
    FUNCTION next_atom_loc
    (string_in IN VARCHAR2,
    start_loc_in IN NUMBER,
    scan_increment_in IN NUMBER := +1)      
    || The next_atom_loc function returns the location
    || in the string of the starting point of the next atomic (from the
    || start location). The function scans forward if scan_increment_in is
    || +1, otherwise it scans backwards through the string. Here is the
    || logic to determine when the next atomic starts:
    ||
    ||          1. If current atomic is a delimiter (if, that is, the character
    ||               at the start_loc_in of the string is a delimiter), then the
    ||               the next character starts the next atomic since all
    ||               delimiters are a single character in length.
    ||
    ||          2. If current atomic is a word (if, that is, the character
    ||               at the start_loc_in of the string is a delimiter), then the
    ||               next atomic starts at the next delimiter. Any letters or
    ||               numbers in between are part of the current atomic.
    ||
    || So I loop through the string a character at a time and apply these
    || tests. I also have to check for end of string. If I scan forward
    || the end of string comes when the SUBSTR which pulls out the next
    || character returns NULL. If I scan backward, then the end of the
    || string comes when the location is less than 0.
    RETURN NUMBER
    IS
    /* Boolean variable which uses private function to determine
    || if the current character is a delimiter or not.
    was_a_delimiter BOOLEAN :=
    PS_Parse.a_delimiter (SUBSTR (string_in, start_loc_in, 1));     
    /* If not a delimiter, then it was a word. */
    was_a_word BOOLEAN := NOT was_a_delimiter;
    /* The next character scanned in the string */
              next_char VARCHAR2(1);
    || The value returned by the function. This location is the start
    || of the next atomic found. Initialize it to next character,
    || forward or backward depending on increment.
    return_value NUMBER := start_loc_in + scan_increment_in;
    BEGIN
    LOOP
    -- Extract the next character.
    next_char := SUBSTR (string_in, return_value, 1);
    -- Exit the loop if:
    EXIT WHEN
    /* On a delimiter, since that is always an atomic */
    a_delimiter (next_char)
    OR
    /* Was a delimiter, but am now in a word. */
    (was_a_delimiter AND NOT a_delimiter (next_char))
    OR
    /* Reached end of string scanning forward. */
    next_char IS NULL
    OR
    /* Reached beginning of string scanning backward. */
    return_value < 0;
    /* Shift return_value to move the next character. */
    return_value := return_value + scan_increment_in;
    END LOOP;
    -- If the return_value is negative, return 0, else the return_value
    RETURN GREATEST (return_value, 0);
    END;
    PROCEDURE increment_counter
    (counter_inout IN OUT NUMBER,
    count_type_in IN VARCHAR2,
    atomic_in IN CHAR)
    || The increment_counter procedure is used by nth_atomic and
    || number_of_atomics to add to the count of of atomics. Since you
    || can request a count by ALL atomics, just the WORD atomics or
    || just the DELIMITER atomics. I use the a_delimiter function to
    || decide whether I should add to the counter. This is not a terribly
    || complex procedure. I bury this logic into a separate module,
    however,
    || to make it easier to read and debug the main body of the programs.
    IS
    BEGIN
    IF count_type_in = 'ALL' OR
    (count_type_in = 'WORD' AND NOT a_delimiter (atomic_in)) OR
    (count_type_in = 'DELIMITER' AND a_delimiter (atomic_in))
    THEN
    counter_inout := counter_inout + 1;
    END IF;
    END increment_counter;
    /* ------------------------- Public Modules -----------------------*/
    PROCEDURE display_atomics
    (table_in IN atoms_tabtype, num_rows_in IN NUMBER)
    || Program to dump out contents of table. Notice I must also pass in
    || the number of rows in the table so that I know when to stop the
    || loop. Otherwise I will raise a NO_DATA_FOUND exception. For a more
    || elaborate display_table module, see Chapter 7 on PL/SQL tables.
    IS
    BEGIN
    FOR table_row IN 1 .. num_rows_in
    LOOP
    DBMS_OUTPUT.PUT_LINE (NVL (table_in (table_row), 'NULL'));
    END LOOP;
    END;
    PROCEDURE parse_string
    (string_in IN VARCHAR2,
    atomics_list_out OUT atoms_tabtype,
    num_atomics_out IN OUT NUMBER,
    delimiters_in IN VARCHAR2 := std_delimiters)
    || Version of parse_string which stores the list of atomics
    || in a PL/SQL table.
    ||
    || Parameters:
    ||          string_in - the string to be parsed.
    ||          atomics_list_out - the table of atomics.
    ||          num_atomics_out - the number of atomics found.
    ||          delimiters_in - the set of delimiters used in parse.
    IS
    BEGIN
    /* Initialize variables. */
    num_atomics_out := 0;
    len_string := string_length (string_in);
    IF len_string IS NOT NULL
    THEN
    || Only scan the string if made of something more than blanks.
    || Start at first non-blank character. Remember: INSTR returns 0
    || if a space is not found. Stop scanning if at end of string.
    start_loc := LEAST (1, INSTR (string_in, ' ') + 1);
    WHILE start_loc <= len_string
    LOOP
    || Find the starting point of the NEXT atomic. Go ahead and
    || increment counter for the number of atomics. Then have to
    || actually pull out the atomic. Two cases to consider:
    ||          1. Last atomic goes to end of string.
    ||          2. The atomic is a single blank. Use special constant.
    ||          3. Anything else.
    next_loc := next_atom_loc (string_in, start_loc);
    num_atomics_out := num_atomics_out + 1;
    IF next_loc > len_string
    THEN
    -- Atomic is all characters right to the end of the string.
    atomics_list_out (num_atomics_out) :=
    SUBSTR (string_in, start_loc);
    ELSE
    || Internal atomic. If RTRIMs to NULL, have a blank
    || Use special-case string to stuff a " " in the table.
    atomics_list_out (num_atomics_out) :=
    NVL (RTRIM (SUBSTR (string_in,
    start_loc, next_loc-start_loc)),
                                       a_blank);
    END IF;
    -- Move starting point of scan for next atomic.
    start_loc := next_loc;
    END LOOP;
    END IF;
    END parse_string;
    PROCEDURE parse_string
    (string_in IN VARCHAR2,
    atomics_list_out IN OUT VARCHAR2,
    num_atomics_out IN OUT NUMBER,
    delimiters_in IN VARCHAR2 := std_delimiters)
    || The version of parse_string which writes the atomics out to a packed
    || list in the format "|A|,|C|". I do not repeat any of the comments
    || from the first iteration of parse_string.
    IS
    BEGIN
    /* Initialize variables */
    num_atomics_out := 0;
    atomics_list_out := NULL;
    len_string := string_length (string_in);
    IF len_string IS NOT NULL
    THEN
    start_loc := LEAST (1, INSTR (string_in, ' ') + 1);
    WHILE start_loc <= len_string
    LOOP
    next_loc := next_atom_loc (string_in, start_loc);
    num_atomics_out := num_atomics_out + 1;
    IF next_loc > len_string
    THEN
    atomics_list_out := atomics_list_out || '|' ||      
    SUBSTR (string_in, start_loc);
    ELSE
    atomics_list_out :=
    atomics_list_out || '|' ||      
    NVL (RTRIM (SUBSTR (string_in,
    start_loc, next_loc-start_loc)),
                                       a_blank);
    END IF;
    start_loc := next_loc;
    END LOOP;
    /* Apply terminating delimiter to the string. */
    atomics_list_out := atomics_list_out || '|' ;
    END IF;
    END parse_string;
    FUNCTION number_of_atomics
    (string_in IN VARCHAR2,
    count_type_in IN VARCHAR2 := 'ALL',
    delimiters_in IN VARCHAR2 := std_delimiters)
    RETURN INTEGER
    || Counts the number of atomics in the string_in. You can specify the
    || type of count you want: ALL for all atomics, WORD to count only the
    || words and DELIMITER to count only the delimiters. You can optionally
    || pass your own set of delimiters into the function.
    IS
    return_value INTEGER := 0;
    BEGIN
    /* Initialize variables. */
    len_string := string_length (string_in);
    IF len_string IS NOT NULL
    THEN
    || This loop is much simpler than parse_string. Call the
    || next_atom_loc to move to the next atomic and increment the
    || counter if appropriate. Everything complicated is shifted into
    || sub-programs so that you can read the program "top-down",
    || understand it layer by layer.
    start_loc := LEAST (1, INSTR (string_in, ' ') + 1);
    WHILE start_loc <= len_string
    LOOP
    increment_counter (return_value, UPPER (count_type_in),
    SUBSTR (string_in, start_loc, 1));
    start_loc := next_atom_loc (string_in, start_loc);
    END LOOP;
    END IF;
    RETURN return_value;
    END number_of_atomics;
    FUNCTION nth_atomic
    (string_in IN VARCHAR2,
    nth_in IN NUMBER,
    count_type_in IN VARCHAR2 := 'ALL',
    delimiters_in IN VARCHAR2 := std_delimiters)
    RETURN VARCHAR2
    || Find and return the nth atomic in a string. If nth_in is greater
    || the number of atomics, then return NULL. If nth_in is negative the
    || function counts from the back of the string. You can again request
    || a retrieval by ALL atomics, just the WORDs or just the DELIMITER.
    || So you can ask for the third atomic, or the second word from the end
    || of the string. You can pass your own list of delimiters as well.
    IS
    /* Local copy of string. Supports up to 1000 characters. */
    local_string VARCHAR2 (1000) :=
    LTRIM (RTRIM (SUBSTR (string_in, 1, 1000)));
    /* Running count of atomics so far counted. */
    atomic_count NUMBER := 1;
    /* Boolean variable which controls the looping logic. */
    still_scanning BOOLEAN :=
    local_string IS NOT NULL AND nth_in != 0;
    /* The amount by which I increment the counter. */
    scan_increment INTEGER;
    /* Return value of function, maximum length of 100 characters. */
    return_value VARCHAR2 (100):= NULL;
    BEGIN
    IF nth_in = 0
    THEN
    /* Not much to do here. Find 0th atomic? */
    RETURN NULL;
    ELSE
    /* Initialize the loop variables. */
    len_string := string_length (local_string);
    IF nth_in > 0
    THEN
    /* Start at first non-blank character and scan forward. */
    next_loc := 1;
    scan_increment := 1;
    ELSE
    /* Start at last non-blank character and scan backward. */
    next_loc := len_string;
    scan_increment := -1;
    END IF;
    /* Loop through the string until the Boolean is FALSE. */
    WHILE still_scanning
    LOOP
    /* Move start of scan in string to loc of last atomic. */
    start_loc := next_loc;
    /* Find the starting point of the next atomic. */
    next_loc      :=
    next_atom_loc (local_string, start_loc, scan_increment);
    /* Increment the count of atomics. */
    increment_counter
    (atomic_count,
    UPPER (count_type_in),
    SUBSTR (local_string, start_loc, 1));
    || Keep scanning if my count hasn't exceeded the request
    || and I am neither at the beginning nor end of the string.
    still_scanning :=
    atomic_count <= ABS (nth_in) AND
    next_loc <= len_string AND
    next_loc >= 1;
    END LOOP;
    || Done with the loop. If my count has not exceeded the requested
    || amount, then there weren't enough atomics in the string to
    || satisfy the request.
    IF atomic_count <= ABS (nth_in)
    THEN
    RETURN NULL;
    ELSE
    || I need to extract the atomic from the string. If scanning
    || forward, then I start at start_loc and SUBSTR forward.
    || If I am scanning backwards, I start at next_loc+1 (next_loc
    || is the starting point of the NEXT atomic and I want the
    || current one) and SUBSTR forward (when scanning in
    || reverse, next_loc comes before start_loc in the string.
    IF scan_increment = +1
    THEN
    RETURN
    SUBSTR (local_string, start_loc, next_loc - start_loc);
    ELSE
    RETURN
    SUBSTR (local_string, next_loc+1, start_loc - next_loc);
    END IF;
    END IF;
    END IF;
    END nth_atomic;
    END PS_Parse;
    /

  • Import CSV Is Incorrect - Misinterprets RETURN within Strings as New Row

    When importing a CSV file into Numbers 3.0.1, it produces bad results, because it interprets RETURNs within strings as new rows, when it should ignore them.
    How can this be worked around?

    If the CSV is properly formatted and the strings that have the carriage return(s) are enclosed in quotes, it works fine  (at least it does for me). If the strings do not have quotes around them, the returns should be interpreted as a new row.
    The workaround would be to somehow get quotes around those strings before importing into Numbers. I'm not sure how to do that except manually in a text editor or for the app that created the CSV to format it correctly.

  • Creating dynamic XML without String var ?

    Hi all...
    I am trying to create a XML to use it in a DataGrid as a
    DataProvider... So far I was able to do it but only using a String
    variable, is there any othe way to do it? I found/think there is
    another way but i'm kinda lost on this subject... Here is how im
    doing it (more or less):
    private var dataPlaylist : XML;
    private var xml : String = new String();
    xml += ' <music>\n';
    xml += ' <artist>' + player.id3.artist +
    '</artist>\n';
    xml += ' <track>' + player.id3.songName +
    '</track>\n';
    xml += ' <title>' + player.id3.title +
    '</title>\n';
    xml += ' <album>' + player.id3.album +
    '</album>\n';
    xml += ' <time>' + player.length + '</time>\n';
    xml += ' </music>\n';
    dataPlaylist = XML(xml);
    playlist.dataProvider = dataPlaylist.musica;

    It's better to read the entire XML documentation located one
    level up:
    http://livedocs.macromedia.com/flex/2/docs/00001910.html
    For your case, you can actually do this:
    dataPlayList: XML =
    <music>
    <artist>{player.id3.artist}</artist>
    <track>{player.id3.songName}</track>
    </music>;
    Note the use of curly braces {} to embed variables inside
    your XML. There's a lot more you can do with XML as well. It's in
    the docs.

Maybe you are looking for

  • [SOLVED]Pacman fails to update

    Hi, It's been a while, so I hope this issue can be resolved here, and I'll be on my best behaviour. I tried an update (system-wide) with pacman -Syu it came back with : error: failed to commit transaction (conflicting files) initscripts: /etc/profile

  • How can sync apple tv with itune library

    how can i sync apple tv 2nd generation with my itunes library?

  • Trouble with Secure Delete Files

    OK, I have upgragded to Tiger and I can't use WMP any longer. I'm a little angry about that, but I'll get over it. I moved WMP to the trash and am trying to do a secure file delete and I get the following error: The operation cannot be completed beca

  • Routing Data Report

    Dear Experts, We have generated the routing data report similar to CA51. FS is as follows: Pass MATNR(Material),WERKS(Plant) & PLNTY(Task list type) to Table MAPL fetch PLNNR(Group) & PLNAL(Gr. Counter).Pass Group & Gr. Counter through Table PLAS and

  • Run-time compiling trouble.

    Hello. I wrote the simple command-prompt program that tries to compile existent java code. Any tries are ends with message: error: Can't read: d:\vcs\tries\test.java 1 error [done in 481 ms] There are code: String[] args = {"-g","-verbose","-classpat