1

If I had a string, say:

String name;

Is there a way I can check each letter with a loop? So if they enter a name can I check what each letter is?

2
  • Why? You can just use System.out.println(name) Commented Sep 16, 2012 at 10:15
  • Despite the number of answers, it's really not clear what you're asking here. I suggest you expand your question, what are you trying to do? Validate the string? Blacklist particular characters? Commented Sep 16, 2012 at 10:17

4 Answers 4

6

There are several ways to do it - you can do a for loop with an index, or a foreach loop on the char[] array:

for (int i = 0 ; i != s.length() ; i++) {
    char c = s.charAt(i);
    ....
}

for (char c : s.toCharArray()) {
    ....
}

In addition to checking each letter separately, you can check all letters at once (or any subset that you'd like) with regular expressions.

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

Comments

3

Use the String.toCharArray() function.

Comments

2
char[] chars = name.toCharArray();
for (int i =0; i < chars.length; i++)
{
    System.out.println(chars[i]);
}

1 Comment

or for(char ch: name.toCharArray())
1

This should do

for ( int i=0 ; i < name.length(); i++)
{
   name.charAt(i);
}

Also read this http://docs.oracle.com/javase/tutorial/java/data/manipstrings.html

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.