This discussion is archived
1 2 Previous Next 16 Replies Latest reply: May 27, 2007 1:03 AM by 807600 RSS

Character arrays to Strings

807599 Newbie
Currently Being Moderated
Hi guys,

I am working on my college assignment and need a bit of assistance.

As part of my solution I have decided to use the methods that come with String objects.Unfortunately I originally coded the project to read in data as characters which were then stored in an array.What I now have is an array of characters which I need to convert into a String so I can use methods such as isWhitespace,length,toLowercase etc.

For example;

char[] string = {'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'};

how would I convert the above to

String converted = new String("This is a string");

PS:I am at the bottom of the programming ladder,so please,the easiest way in which I can
build from.

Thanks
  • 1. Re: Character arrays to Strings
    masijade Explorer
    Currently Being Moderated
    char[] string = {'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'};
    String converted = new String(string);
    Read the API. String can take a char[] in its constructor.
  • 2. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    Thanks for the prompt reply.Will investigate that immediately!
  • 3. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    Marvellous.It worked,however I have introduced a problem I did not anticipate.

    I had to initialise the character array so it is of a fixed length [300].One of the reasons I wanted to change the array to a String was to use the String.length() function (amongst others) to count the number of characters inputted.

    Now since I changed it from a character array it includes all the null values hence the length remains [300].Is there any way of getting rid of the null values so I only remain with inputted text?

    ie
    int temp;
    inputFile = file;//will be getting this from an argument
    int i=0;
    char[] textFromFile = new char[300]

    try
    {
    BufferedReader bGetFile = new BufferedReader (new FileReader(inputFile));
    while ((temp=bGetFile.read())!=-1)
    {
    textFromFile[i] = (char)temp;
    i++;
    }

    inputText=new String(textFromFile);
    bGetFile.close();
    }
    catch (IOException e)
    {
    System.out.println (" ");
    System.out.println ("Sorry.An error occurred while trying to read from the input
    file.Unable to proceed!");
    }


    return inputText;

    What I want is only the non-null values in inputText.
  • 4. Re: Character arrays to Strings
    masijade Explorer
    Currently Being Moderated
    char[] string = {'T','h','i','s',' ','i','s',' ','a',' ','s','t','r','i','n','g'};
    String converted = new String(string).trim();
    note: this will also remove leading whitespace.
  • 5. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    trim() only removes leading and trailing whitespace. He could use a replace() method to get rid on unwanted characters.
  • 6. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    Wonderful!

    Thanks very much.All now works as it should.
  • 7. Re: Character arrays to Strings
    masijade Explorer
    Currently Being Moderated
    [url=http://java.sun.com/j2se/1.5.0/docs/api/java/lang
    /String.html#trim()]trim() only removes leading
    and trailing whitespace. He could use a
    [url=http://java.sun.com/j2se/1.5.0/docs/api/java/lang
    /String.html#replace(char,%20char)]replace()
    method to get rid on unwanted characters.
    Well, he was asking about the null characters at the end of the array, so I figured that was the easiest, and quickest.
  • 8. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    Well, he was asking about the null characters at the
    end of the array, so I figured that was the easiest,
    and quickest.
    Whoops, I thought he had null characters somewhere in the middle. You were right. ;-)
  • 9. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    The assignment was to write a program to analyse a passage of text from a text file.

    Writing and testing the bits of code has worked so far but I'm now having problems with the complete program.I still have to do work with the vowelFrquency method but for now I would have expected the rest of the code to work.It compiles but hangs when run.I have gone through it but can't find what I'm doing wrong.I suspect logic errors in the 'count' methods.Could you please look through it and advise.

    The program consists of a class TextAnalyzer and a driver class TextAnalyzerTest as shown below;


    import java.io.*;//140407 0124 required to deal with getting text input
    public class TextAnalyzer //The class that will be doing most of the work for this project
    {
    private String textToBeRead;
    /*100407 0411 Still have to figure how to use arguments to enable the text to be processed to be either console input or from
    * file.My idea here is to make the application flexible enough to take a file to be read from the console via argument or to
    * read text typed in directly from console.*/

    private String inputFile= new String("");
    private String inputText= new String("");
    private int printable;//count of printable text
    private int whitespace;//count of whitespace in passage
    private int vowels;//count of vowels
    private int consonants;//count of consonants
    private int MAX=300;//variable to hold maximum printable characters
    private char textFromFile[]=new char[MAX];

    private int frequency[] = new int[5];//array to hold frequency of vowels

    public TextAnalyzer() //Constructor.100407 0444,I might want to consider constructor overloading to use parameters?
    {
    textToBeRead = "";
    printable = 0;
    whitespace = 0;
    vowels = 0;
    consonants = 0;
    MAX = 300;
    int frequency[] = {0,0,0,0,0};

    for (int i=0;i<MAX;i++)//added 14042007 0147 to intialize array which will act as a buffer
    {
    textFromFile[i] = 0;
    }

    }

    public String getText (String file)//textfile to be analyzed will be inputted as argument 150407 0356

    //15042007 0612 Check notes on overloaded getText method below.
    {
    int temp;
    inputFile = file;
    int i=0;

    try
    {
    BufferedReader bGetFile = new BufferedReader (new FileReader(inputFile));
    while ((temp=bGetFile.read())!=-1)
    {
    textFromFile[i] = (char)temp;
    i++;
    }
    /*for (int j=0;j<MAX;j++)
    {
    System.out.print(textFromFile[j]);//25042007 0208.For Testing purposes
    }
    */
    inputText=new String(textFromFile).trim();
    bGetFile.close();
    }
    catch (IOException e)
    {
    System.out.println (" ");
    System.out.println ("Sorry.An error occurred while trying to read from the input file.Unable to proceed!");
    }


    return inputText;


    }
    /*public void getText ()//text taken from keyboard input

    *Class tested and working fine 15042007 0605.Need to research truncation,as files larger than 300 characters will throw
    * an ArrayOutOfBounds Exception error.I might have to set the character size in this method i.e read in the original text
    * file in its entirety then chop it in this method.
    *
    *

    {
    int temp;
    int i=0;

    {
    try
    {
    BufferedReader bGetFile = new BufferedReader (new InputStreamReader (System.in));
    while ((temp=bGetFile.read())!=NULL)
    {
    textFromFile[i] = (char)temp;
    i++;
    }
    System.out.print(textFromFile);
    bGetFile.close();
    }
    catch (IOException e)
    {
    System.out.println("\nSorry.Unable to read from input device.Cannot proceed!");
    }

    }


    }*/

    public int countPrintable()
    {
    //some code to give list of all printable characters and compare to given text.
    //count and adjust value of printable accordingly
    int totalChars=inputText.length();
    printable=totalChars-whitespace;
    return printable;
    }

    public int countWhiteSpace()
    {
    //some code to give list of all whitespace characters and compare to given text.
    //count and adjust value of whitespace accordingly
    for (int w=0;w<inputText.length();w++)
    {
    char ch = inputText.charAt(w);
    while (Character.isWhitespace(ch))
    {
    whitespace++;
    }
    }
    return whitespace;
    }

    public int countVowels()
    {
    //some code to give list of all vowels and compare to given text.
    //count and adjust value of vowels accordingly
    for (int w=0;w<inputFile.length();w++)
    {
    inputText.toLowerCase();
    char ch = inputText.charAt(w);
    if ((ch=='a')||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u'))
    {
    vowels++;
    }
    }
    return vowels;
    }

    public int countConsonants()
    {
    //some code to give list of all consonants and compare to given text.
    //count and adjust value of consonants accordingly
    for (int w=0;w<inputText.length();w++)
    {
    int numLetters=0;
    char ch =inputText.charAt(w);
    while (Character.isLetter(ch))
    {
    numLetters++;
    }
    consonants=numLetters-vowels;
    }
    return consonants;
    }

    public int vowelFrequency()
    {
    //some code to place vowel frequencies in an array.
    //will use normal sequence of vowels for the array ie a,e,i,o,u to determine index correlation
    //ie a corresponds to index 0,e corresponds to 1,i coreesponds to 2 etc.
    //adjust value of frequency
    for (int w=0;w<inputText.length();w++)
    {
    inputFile.toLowerCase();
    char ch = inputFile.charAt(w);
    if (ch=='a')
    {
    frequency[0]++;
    }
    else if (ch=='e')
    {
    frequency[1]++;
    }
    else if (ch=='i')
    {
    frequency[2]++;
    }
    else if (ch=='o')
    {
    frequency[3]++;
    }
    else if (ch=='u')
    {
    frequency[4]++;
    }

    }
    return frequency[5];
    }

    public void displayAnalysis ()
    {
    System.out.println ("====================================================================");
    System.out.println ("====================================================================");
    System.out.println ("Analysis results ...................................................");
    System.out.println ("Number of printable characters were "+ printable);
    System.out.println ("Number of consonants were "+ consonants);
    System.out.println ("Number of vowels were "+ vowels);
    System.out.println ("Number of whitespace characters were " + whitespace);
    System.out.println ("");
    System.out.println ("Thank you for using TextAnalyzerTest ...............................");
    }

    }


    /**
    * This is the test harness for the TestAnalyzer class.
    *
    * This class is being developed alongside the TestAnalyzer class.I have taken the more complicated
    * option of designing the program as I go.By rights this program should be planned before coding
    * but unfortunately I just cannot seem to plan it and have decided to just jump in and get it done.
    * I have tried to add 'development' notes as I go :-)
    */
    public class TextAnalyzerTest
    {
    public static void main (String args[])
    {
    TextAnalyzer analyze = new TextAnalyzer();
    if (args.length>0)
    {
    analyze.getText(args[0]);
    analyze.countConsonants();
    analyze.countVowels();
    analyze.countWhiteSpace();
    analyze.countPrintable();
    analyze.displayAnalysis();
    }
    else
    {
    System.out.println("Sorry the input file cannot be found.Please check you system and ensure you are entering the file correctly");
    System.out.println("");
    System.out.println("");
    System.out.println("Usage:TestAnalyzerTest FileToBeAnalyzed");
    }

    }
    }
  • 10. Re: Character arrays to Strings
    masijade Explorer
    Currently Being Moderated
    Please repost your code using code tags. I responded to your previous post so that you simply edit your last post (rather than adding a new post). Delete out the code, then press the "code" button above the window where you type, and paste the code in again (from the src), between the resulting tags.
  • 11. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    Please repost your code using code tags. I responded
    to your previous post so that you simply edit your
    last post (rather than adding a new post). Delete
    out the code, then press the "code" button above the
    window where you type, and paste the code in again
    (from the src), between the resulting tags.
    Sorry about that.Still finding my way around :-(

    I can't seem to delete out the code from the previous posting.
    import java.io.*;//140407 0124 required to deal with getting text input
    public class TextAnalyzer //The class that will be doing most of the work for this project
    {
    private String textToBeRead;
    /*100407 0411 Still have to figure how to use arguments to enable the text to be processed to be either console input or from
    * file.My idea here is to make the application flexible enough to take a file to be read from the console via argument or to
    * read text typed in directly from console.*/
    
    private String inputFile= new String("");
    private String inputText= new String("");
    private int printable;//count of printable text
    private int whitespace;//count of whitespace in passage
    private int vowels;//count of vowels
    private int consonants;//count of consonants
    private int MAX=300;//variable to hold maximum printable characters
    private char textFromFile[]=new char[MAX];
    
    private int frequency[] = new int[5];//array to hold frequency of vowels
    
    public TextAnalyzer() //Constructor.100407 0444,I might want to consider constructor overloading to use parameters?
    {
    textToBeRead = "";
    printable = 0;
    whitespace = 0;
    vowels = 0;
    consonants = 0;
    MAX = 300;
    int frequency[] = {0,0,0,0,0};
    
    for (int i=0;i<MAX;i++)//added 14042007 0147 to intialize array which will act as a buffer
    {
    textFromFile = 0;
    }
    
    }
    
    public String getText (String file)//textfile to be analyzed will be inputted as argument 150407 0356
    
    //15042007 0612 Check notes on overloaded getText method below.
    {
    int temp;
    inputFile = file;
    int i=0;
    
    try
    {
    BufferedReader bGetFile = new BufferedReader (new FileReader(inputFile));
    while ((temp=bGetFile.read())!=-1)
    {
    textFromFile = (char)temp;
    i++;
    }
    /*for (int j=0;j<MAX;j++)
    {
    System.out.print(textFromFile[j]);//25042007 0208.For Testing purposes
    }
    */
    inputText=new String(textFromFile).trim();
    bGetFile.close();
    }
    catch (IOException e)
    {
    System.out.println (" ");
    System.out.println ("Sorry.An error occurred while trying to read from the input file.Unable to proceed!");
    }
    
    
    return inputText;
    
    
    }
    /*public void getText ()//text taken from keyboard input
    
    *Class tested and working fine 15042007 0605.Need to research truncation,as files larger than 300 characters will throw
    * an ArrayOutOfBounds Exception error.I might have to set the character size in this method i.e read in the original text
    * file in its entirety then chop it in this method.
    *
    *
    
    {
    int temp;
    int i=0;
    
    {
    try
    {
    BufferedReader bGetFile = new BufferedReader (new InputStreamReader (System.in));
    while ((temp=bGetFile.read())!=NULL)
    {
    textFromFile = (char)temp;
    i++;
    }
    System.out.print(textFromFile);
    bGetFile.close();
    }
    catch (IOException e)
    {
    System.out.println("\nSorry.Unable to read from input device.Cannot proceed!");
    }
    
    }
    
    
    }*/
    
    public int countPrintable()
    {
    //some code to give list of all printable characters and compare to given text.
    //count and adjust value of printable accordingly
    int totalChars=inputText.length();
    printable=totalChars-whitespace;
    return printable;
    }
    
    public int countWhiteSpace()
    {
    //some code to give list of all whitespace characters and compare to given text.
    //count and adjust value of whitespace accordingly
    for (int w=0;w<inputText.length();w++)
    {
    char ch = inputText.charAt(w);
    while (Character.isWhitespace(ch))
    {
    whitespace++;
    }
    }
    return whitespace;
    }
    
    public int countVowels()
    {
    //some code to give list of all vowels and compare to given text.
    //count and adjust value of vowels accordingly
    for (int w=0;w<inputFile.length();w++)
    {
    inputText.toLowerCase();
    char ch = inputText.charAt(w);
    if ((ch=='a')||(ch=='e')||(ch=='i')||(ch=='o')||(ch=='u'))
    {
    vowels++;
    }
    }
    return vowels;
    }
    
    public int countConsonants()
    {
    //some code to give list of all consonants and compare to given text.
    //count and adjust value of consonants accordingly
    for (int w=0;w<inputText.length();w++)
    {
    int numLetters=0;
    char ch =inputText.charAt(w);
    while (Character.isLetter(ch))
    {
    numLetters++;
    }
    consonants=numLetters-vowels;
    }
    return consonants;
    }
    
    public int vowelFrequency()
    {
    //some code to place vowel frequencies in an array.
    //will use normal sequence of vowels for the array ie a,e,i,o,u to determine index correlation
    //ie a corresponds to index 0,e corresponds to 1,i coreesponds to 2 etc.
    //adjust value of frequency
    for (int w=0;w<inputText.length();w++)
    {
    inputFile.toLowerCase();
    char ch = inputFile.charAt(w);
    if (ch=='a')
    {
    frequency[0]++;
    }
    else if (ch=='e')
    {
    frequency[1]++;
    }
    else if (ch=='i')
    {
    frequency[2]++;
    }
    else if (ch=='o')
    {
    frequency[3]++;
    }
    else if (ch=='u')
    {
    frequency[4]++;
    }
    
    }
    return frequency[5];
    }
    
    public void displayAnalysis ()
    {
    System.out.println ("====================================================================");
    System.out.println ("====================================================================");
    System.out.println ("Analysis results ...................................................");
    System.out.println ("Number of printable characters were "+ printable);
    System.out.println ("Number of consonants were "+ consonants);
    System.out.println ("Number of vowels were "+ vowels);
    System.out.println ("Number of whitespace characters were " + whitespace);
    System.out.println ("");
    System.out.println ("Thank you for using TextAnalyzerTest ...............................");
    }
    
    }
    The test harness:
    /**
    * This is the test harness for the TestAnalyzer class.
    *
    * This class is being developed alongside the TestAnalyzer class.I have taken the more complicated
    * option of designing the program as I go.By rights this program should be planned before coding
    * but unfortunately I just cannot seem to plan it and have decided to just jump in and get it done.
    * I have tried to add 'development' notes as I go :-)
    */
    public class TextAnalyzerTest
    {
    public static void main (String args[])
    {
    TextAnalyzer analyze = new TextAnalyzer();
    if (args.length>0)
    {
    analyze.getText(args[0]);
    analyze.countConsonants();
    analyze.countVowels();
    analyze.countWhiteSpace();
    analyze.countPrintable();
    analyze.displayAnalysis();
    }
    else
    {
    System.out.println("Sorry the input file cannot be found.Please check you system and ensure you are entering the file correctly");
    System.out.println("");
    System.out.println("");
    System.out.println("Usage:TestAnalyzerTest FileToBeAnalyzed");
    }
    
    }
    }
  • 12. Re: Character arrays to Strings
    masijade Explorer
    Currently Being Moderated
    At a quick glance it seems to be okay (nothing that JUMPS out at me anyway). Try running it through a debugger, or add a few System.out.println() statements before and after each method call to find out how far it gets.
  • 13. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    At a quick glance it seems to be okay (nothing that
    JUMPS out at me anyway). Try running it through a
    debugger, or add a few System.out.println()
    statements before and after each method call to find
    out how far it gets.
    After a bit of debugging I am convinced part of my problem may be here;
    public int countConsonants()
       {
           System.out.println ("This is the countConsonants method"); //25042007 2318 being used for debugging purposes 
           //some code to give list of all consonants and compare to given text.
           //count and adjust value of consonants accordingly
           int numLetters=0;
           
           for (int w=0;w<inputText.length();w++)
            {
                char ch = inputText.charAt(w);
                while (Character.isLetter(ch))
                {
                    numLetters++;
                }
            }
            
           consonants=numLetters-vowels;
           System.out.println ("This is the number of consonants method: "+ consonants); //25042007 2318 being used for debugging purposes
           System.out.println ("This is the number of letters: "+ numLetters); //25042007 2318 being used for debugging purposes
           return consonants;
       }
    I have a feeling my while loop may be an infinite loop but logically it seems fine.I will quickly check up on while and if statements and see if I can re-write the code in a better way.In the meantime any suggestions would be appreciated.
  • 14. Re: Character arrays to Strings
    807599 Newbie
    Currently Being Moderated
    Yes!

    I substituted the while loops for if loops and it's working now.Just need to do a bit of tweaking and maybe later try and add a GUI interface (though i think I will leave this for a distant project!).

    Thanks a lot masijade you have been a tremendous help!
1 2 Previous Next