0

Can you include / interpret spaces from .toCharArray ..

Right now it skips the spaces..

    char[] first = first_string.toCharArray();

for (int x = 0; x < first.length; x++) {
        char first_letter = first[x];
 }

first_letter doesn't include the spaces ..?

2
  • What is first_string? Commented Jan 12, 2014 at 0:39
  • 1
    The problem is almost certainly in where you're getting first_string from, not in this code. Commented Jan 12, 2014 at 0:39

2 Answers 2

3

You are confused. String.toCharArray() does not remove or "skip" spaces. It delivers exactly the sequence of characters as they are in the String.

The most likely problem is that the (expected) leading space is not in that string (first_string) at all. You can check by temporarily adding this line:

    System.err.println("first_string is '" + first_string + "'");

and looking at the output. Or you could use a debugger to set a breakpoint and examine the value of first_string directly.


Hints for debugging:

If your program misbehaves in a way that you can't explain / understand, then question your assumptions:

  • Read / reread the javadocs to check that the library methods you are using actually do what you think / remember they do.

  • Check that the relevant variables have the values that you think they should have.

And ... learn how to use your IDE's debugger, 'cos you will save lots of time if you can use a debugger effectively.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 because, on top of the info I provided below, a good suggestion for using the debugger. This is the perfect time for @Ds. 109 to get comfortable with debugging.
0

Yes, it does include spaces by default. For example,

public class Tester {
    public static void main (String[] args) {
        String temp = "This is a sentence.";
        char[] arr = temp.toCharArray();

        for (char k : arr) {
            System.out.print(k);
        }
    }
}

Prints out "This is a sentence." You should always consult the Javadocs when in doubt about what a function does. Take a look at this: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#toCharArray()

Which quotes directly: "a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.