The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

Java, string to char

oniianoniian Registered User regular
edited December 2006 in Help / Advice Forum
Whats the best way to convert a string, e.g. "I have a dog named bob," to char? The ways I can think of is:

String dog = "I have a dog named bob";

then using a for loop to change each letter to a char

for(int i = 0, i < dog.length(), i++)
{
char dogName = dog.charAt(i);
}

or

char[] dogName = dog.toCharArray();

Is any better ways like parsing it? and if I use toCharArray(), can I still use charAt for later comparisons or do I have use the array index instead of the position of the char in the sentence?

oniian on

Posts

  • KismetKismet Registered User regular
    edited December 2006
    I would just use the toCharArray() function - it's more concise and readable.
    As for later comparisons, do you mean with the string or with the character array?

    for the string, charAt would be fine, for the char array you'd use the index.
    Assuming the data in both hasn't changed, it's really doing the same thing.
    dog.charAt(4) and dogName[4] would mean the same thing in that case.

    Why do you want to copy it? Do you need to parse it?
    From your post it seems like you have a good understanding of the example you posted. What exactly do you need to do here?

    Kismet on
  • oniianoniian Registered User regular
    edited December 2006
    Kismet wrote:
    What exactly do you need to do here?

    Fulfill my plans for world domination. (man thats lame)

    Actually this part of an assignment where I am suppose to take in user input and return the number of times every letter used appears in the input in alphabetical order. Not to hard really but I was trying to get the length of the input to use as a termination clause in a for loop and I haven't found a method to get the length of char like the length method for String in my book. A friend said she tried using one but it didn't work properly. So what I was going to do is just have the input come in as a string, find the length, and then convert it to char for the comparisons and calculations.

    oniian on
  • oniianoniian Registered User regular
    edited December 2006
    Which I guess leads to the better question: is there a method out there finds the length of a series of char?

    oniian on
  • DeswaDeswa Registered User regular
    edited December 2006
    oniian wrote:
    Which I guess leads to the better question: is there a method out there finds the length of a series of char?
    I might be wrong here, but couldn't you do:
    while ( string.hasNextChar() )
         {
         count++
         }
    
    Or something like that? I remember being able to do that with strings, I just dont have my book on me to check that out.

    Deswa on
    gobassgo wrote:
    "It ain't rape, it's surprise sex!"
    wii : 3788 3264 2419 8070
  • ffordefforde Registered User regular
    edited December 2006
    You are making this more complicated than it needs to be. You just need something like:

    for (int i = 0; i < myString.length(); i++) {

    }


    That loop will step through the whole string, and inside it, myString.charAt(i) will give you the current character. Now you just need to come up with a way to keep a tally for how many times you see each character.

    EDIT: oops it is length() not size() fixed it above

    fforde on
  • shadowaneshadowane Registered User regular
    edited December 2006
    I'm kind of confused what you are trying to do here, but here's some things I'll just throw out there and see if you can use them.

    String:
    string.length() will give you length of the string.
    string.toCharArray() will return an array of chars for the string. So you'd end up with Char[] stringInChars.

    Char[]:
    Obviously here you can do stringInChars.length as well. Gets you how many characters were in the string. It probably includes spaces just so you know.

    For the project, you could probably just use a TreeMap built from your character array which would give you a sorted list of the characters. Then count from there.

    shadowane on
  • DeswaDeswa Registered User regular
    edited December 2006
    fforde wrote:
    Now you just need to come up with a way to keep a tally for how many times you see each character.

    I'd suggest a switch statement,
    switch (charresult) {
    case a: a++ //increases variable a per a found.
    }

    Deswa on
    gobassgo wrote:
    "It ain't rape, it's surprise sex!"
    wii : 3788 3264 2419 8070
  • oniianoniian Registered User regular
    edited December 2006
    fforde wrote:
    ... and inside it, myString.charAt(i) will give you the current character.

    The reason I mention char in the first places is when I go to do the tally I will use the unicode integer values for letters in upper case to create an array that will increment the the proper part of the index ( 'A' - 67 = 0 which will be the index) using the a for loop to compare the unicode value to the char sequentially. (if you follow me) I want the input ti be in char to tally it easily but I need the length for the loop.

    I hope that clears up what I am trying to do, sorry if confusing. Maybe I should just post the actual problem description so I am not speaking in fragments.

    oniian on
  • oniianoniian Registered User regular
    edited December 2006
    Deswa wrote:
    I'd suggest a switch statement...

    That would work but by using the unicode and char I wouldn't have to write out every letter I am testing for.

    oniian on
  • ffordefforde Registered User regular
    edited December 2006
    oniian wrote:
    fforde wrote:
    ... and inside it, myString.charAt(i) will give you the current character.

    The reason I mention char in the first places is when I go to do the tally I will use the unicode integer values for letters in upper case to create an array that will increment the the proper part of the index ( 'A' - 67 = 0 which will be the index) using the a for loop to compare the unicode value to the char sequentially. (if you follow me) I want the input ti be in char to tally it easily but I need the length for the loop.

    I hope that clears up what I am trying to do, sorry if confusing. Maybe I should just post the actual problem description so I am not speaking in fragments.

    The array idea sounds good. myString.charAt(index) gives you a char type. Then use Character.getNumericValue(char) to get the unicode integer.

    EDIT: And remember to convert everything to uppercase (or lower case either one) before you tally a value unless you want it to be case sensitive. Since uppercase 'A' and lowercase 'a' have different unicode values.

    fforde on
  • oniianoniian Registered User regular
    edited December 2006
    Maybe I am being lazy but is there away to convert everything at once (i.e. not having to use a loop with charAt()) to char after I get the length from the string?

    oniian on
  • ffordefforde Registered User regular
    edited December 2006
    oniian wrote:
    Maybe I am being lazy but is there away to convert everything to char after I get the length from the string?

    Two solutions have already been offered in this thread. A loop with charAt(i) and the toCharArray() method. I am not sure what you are trying to do that these methods don't do.

    fforde on
  • vonPoonBurGervonPoonBurGer Registered User regular
    edited December 2006
    I'd try doing it with a hashtable. For each character in the string, you look in the hashtable using containsKey(). If you find that character as a hashtable key, you get the integer value associated with the key, increment it by one, and then update that hashtable key with the new value. If you don't find that character as a hashtable key, you add it as a new key, and assign its associated integer value as 1. After you're done looping through all the characters (whether you choose to do that with charAt() and a loop based on string length, or an array of chars using toCharArray()), you can get all the hashtable keys using keys(), loop through all those keys, retrieve their associated integer values, and print out key -> value pairs, e.g.:
    a = 3
    b = 1
    ; = 1
    etc.
    
    Even if someone uses a wacky special character, you end up with a key-value pair that essentially says "wacky special character" -> 1, and you don't have to specifically code for that case. I'd try writing out some sample code, but my Java is way rusty these days.

    vonPoonBurGer on
    Xbox Live:vonPoon | PSN: vonPoon | Steam: vonPoonBurGer
  • oniianoniian Registered User regular
    edited December 2006
    fforde wrote:
    I am not sure what you are trying to do that these methods don't do.
    oniian wrote:
    Is any better ways (doing it)?

    It comes down to trying to do in one line of code what it would take to do in a for loop or creating a second array. IOW, keep the code as short and simple as possible for better and more efficent coding.

    Trying find out if there is something to the convert a variable reference to an entire string to char or some methods that calculate the length of a line char. Or at the very least increase my knowledge of different methods that are out there and not cover by the book I own.

    I knew of the two solutions already as mention in my orginal post, I just want to know if anyone else had more ideas other than charAt() and toCharArray().

    oniian on
  • ffordefforde Registered User regular
    edited December 2006
    oniian wrote:
    fforde wrote:
    I am not sure what you are trying to do that these methods don't do.
    oniian wrote:
    Is any better ways (doing it)?

    It comes down to trying to do in one line of code what it would take to do in a for loop or creating a second array. IOW, keep the code as short and simple as possible for better and more efficent coding.

    Trying find out if there is something to the convert a variable reference to an entire string to char or some methods that calculate the length of a line char. Or at the very least increase my knowledge of different methods that are out there and not cover by the book I own.

    I knew of the two solutions already as mention in my orginal post, I just want to know if anyone else had more ideas other than charAt() and toCharArray().

    A char is a data type of one character. The length is always one. actually it is more accurate to say that it has no length. Length only comes in to play if you have an array of chars. You cant convert a String to a char because a String is a representation of many chars. Saying you want to convert a String to a char is like saying you want to convert a house to a brick.

    You are going to have to loop through all the chars in the String though to tally the char count of each character.

    If you want to learn new methods check out Sun's JavaDocs for the Java API. The docs for the String class are here.

    fforde on
  • blincolnblincoln Registered User regular
    edited December 2006
    I'd try doing it with a hashtable

    Seriously. I'm surprised that wasn't more peoples' immediate response.

    I'm rusty in Java, so here's one method in pseudo-C#:

    Hashtable charTable = new Hashtable

    for (int i = 0; i < inString.Length; i++)
    {
    char currentChar = (char)inString.Substring(i, 1);
    if (!charTable.Contains(currentChar))
    {
    charTable.Add(currentChar, 0);
    }
    charTable(currentChar)++;
    }

    blincoln on
    Legacy of Kain: The Lost Worlds
    http://www.thelostworlds.net/
  • oniianoniian Registered User regular
    edited December 2006
    hmmm.... make sense to me. But there doesn't seem to been anyway to count the number char in a char type variable reference like there is for a string variables, is there?



    Edit: oh man, I got to get going but I'll be back on later and see what more collective knowledge I can try to gain.

    Uggghhhh Meant variable, not object.

    oniian on
  • Jimmy KingJimmy King Registered User regular
    edited December 2006
    oniian wrote:
    hmmm.... make sense to me. But there doesn't seem to been anyway to count the number char in a char type object reference like there is for a string objects, is there?
    eh? there could only ever be 1 in a char object. If you have more than one character it becomes a string.

    Jimmy King on
  • KismetKismet Registered User regular
    edited December 2006
    blincoln wrote:
    I'd try doing it with a hashtable

    Seriously. I'm surprised that wasn't more peoples' immediate response.

    I'm rusty in Java, so here's one method in pseudo-C#:

    Hashtable charTable = new Hashtable

    for (int i = 0; i < inString.Length; i++)
    {
    char currentChar = (char)inString.Substring(i, 1);
    if (!charTable.Contains(currentChar))
    {
    charTable.Add(currentChar, 1);
    }
    charTable(currentChar)++;
    }
    You would want to initialize to 0, so that when it increments it goes to 1.
    alternatively, put an else before the increment.

    edit - I think few people mentioned a hash table because they aren't generally covered extensively, if at all in beginning courses.
    I didn't even know what a hashtable was until I started ruby, which is awesome btw.

    Kismet on
  • blincolnblincoln Registered User regular
    edited December 2006
    Kismet wrote:
    You would want to initialize to 0, so that when it increments it goes to 1.

    Whoops, yeah, good point, thanks. Fixed.

    I don't know if there's an equivalent in Java, but I was thinking in C# I might use an Arraylist for this, so I could use the built in sort to put it in alphabetical order.

    Edit: I really wish more beginning dev courses covered standard collection types like hashtables and stacks. They're really useful, and almost no one seems to know about them.

    blincoln on
    Legacy of Kain: The Lost Worlds
    http://www.thelostworlds.net/
  • ffordefforde Registered User regular
    edited December 2006
    blincoln wrote:
    Seriously. I'm surprised that wasn't more peoples' immediate response.

    He said he was going to use an array, which would work just fine. He was asking for help parsing his String, not how to store his numbers.

    fforde on
  • blincolnblincoln Registered User regular
    edited December 2006
    fforde wrote:
    He said he was going to use an array, which would work just fine. He was asking for help parsing his String, not how to store his numbers.

    It would *work*, but it would require a lot more effort on his part. It's like using Excel when you should be using Access. It *works* for most things, but it's not the ideal tool for the job.

    Using a hashtable means he doesn't have to pre-define an array that will probably be much bigger than he actually needs, especially in Unicode.

    blincoln on
    Legacy of Kain: The Lost Worlds
    http://www.thelostworlds.net/
  • ffordefforde Registered User regular
    edited December 2006
    blincoln wrote:
    fforde wrote:
    He said he was going to use an array, which would work just fine. He was asking for help parsing his String, not how to store his numbers.

    It would *work*, but it would require a lot more effort on his part. It's like using Excel when you should be using Access. It *works* for most things, but it's not the ideal tool for the job.

    Using a hashtable means he doesn't have to pre-define an array that will probably be much bigger than he actually needs, especially in Unicode.
    Integer[] counts = new Integer[256];
    
    // code to populate array
    
    for (int i = 0; i < counts.length; i++) {
      if (counts[i] != 0)  
        System.out.println((char)i + ": " + counts[i]);
    } 
    

    That is super complex man, let me tell you. Wasting a lot of extra memory there too.

    I am not saying using a HashTable is a bad way to go, thats probably how I would do it. But he is already asking for help on a message board. There is no reason to give him a whole new data structure to learn, in addition to the trouble he is already having. An array works just fine.

    fforde on
  • DrFrylockDrFrylock Registered User regular
    edited December 2006
    With respect to iterating over the characters of a string: you can iterate through the string and use charAt() or you can toCharArray it and iterate over the character array. The latter approach will use a small amount more memory.

    To determine the length of a char[], use the .length attribute implicitly present on every Java array:

    String s = "some string";
    char[] schars = s.toCharArray();
    int len = schars.length;

    With respect to the storage of counts, it depends on the character (pun intended) of the assignment.

    If we assume that the Strings are unicode and can contain any character and that we have to count them all separately, a Hashtable is not a bad data structure to use (although you'll have to sort them manually later, which is not ideal, using a sorted data structure like a tree might be better). Using an array is slightly more efficient but burns 16384 ints (or shorts, or longs) of memory since there are 16384 possible unicode values in a character set if I recall correctly.

    If we assume that the strings will consist of only ASCII characters (0-255 values) then you can just use an int[256] to tally each character as you parse it, and then iterate through the integer array.

    If we assume that we can ignore punctuation, spaces, and just count letters, then you can use an array of int[26*2] for upper and lowercase.

    If we assume that we can ignore case as well, you can use an array of int[26] and then toLowerCase the String before processing it.

    DrFrylock on
  • mrcheesypantsmrcheesypants Registered User regular
    edited December 2006
    For any questions about java class methods:

    The docs are your friend

    Be sure to bookmark that page if you haven't downloaded the docs.

    mrcheesypants on
    Diamond Code: 2706 8089 2710
    Oh god. When I was younger, me and my friends wanted to burn the Harry Potter books.

    Then I moved to Georgia.
  • CentipeedCentipeed Registered User regular
    edited December 2006
    I don't see why you can't just compare to another char value, and not even worry about converting to char arrays:

    for (int i = 0; i < string.length(); i++)
    {
    if (string.charAt(i) = "a") lettercount++;
    }

    I mean, do you need to use unicode values? Because you could just compare directly, and it takes about 4 billion lines less than the other solutions.

    Edit: I just re-read what he's trying to do, and comparing every letter in the string with every letter in the alphabet would work, and it'd be simple, but it'd be a lot of code.

    Centipeed on
Sign In or Register to comment.