-1

I have two Strings: temp and message. I want to be able to cycle through message with a for loop, and with each iteration set temp equal to the character at the index i of message, like so:

for (int i = 0; i <= message.length(); i++) {
        temp = //something here to indicate the character at i in message.
    }

How would I do this?

Ethan Stedman
  • 11
  • 1
  • 6

5 Answers5

0

You can use the String.charAt() method, which will return the character at a specific index in a string, in your for loop.

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Edit to add: This will get you the character at the index you want in your original string. For your temp string, you would either want to utilize an array of characters (as other users have said), or use string concatenation to keep adding characters at the end (not recommended, but possible)

0

I would convert the message String into a char array with String's toCharArray() method, then iterate through that array, setting temp to arr[i] each time. If you need temp to be a String specifically, use String.valueOf(arr[i]) instead.

Bynine
  • 21
  • 7
0

You can use String method charAt like this:

for (int i = 0; i <= message.length(); i++) {
    temp = message.charAt(i);
}
Facundo Larrosa
  • 3,349
  • 2
  • 14
  • 22
0
String message = "test";
for (int i = 0; i < message.length(); i++) {
    char temp = message.charAt(i);
    System.out.println(temp);
}
Pavel Molchanov
  • 2,299
  • 1
  • 19
  • 24
  • You must add some explanation when you answer. Code only answers are not recommended. – Pritam Banerjee Jul 17 '18 at 23:27
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – jay.sf Jul 17 '18 at 23:34
0

You can use the String.charAt() method on the string. We can encapsulate that method inside of the String.valueOf function which will convert it to a string. Then you can store each element inside of the temp string. Although, with the looks of this program, i'm not sure why you don't just make temp a char? As an argument it will take the index of the character that you want to extract from the string. We can pass "i" as the argument each time through the for loop. You also need to say "i < message.length" in your conditional statement within the for loop because String indexes start at 0 in Java just like array indexes. Here is an example:

public static void main(String[] args) {

            String message = "message";
            String temp = "";


    for (int i = 0; i < message.length(); i++) {
        temp = String.valueOf(message.charAt(i));
        System.out.print(temp);
    }
}

As you can see, we have to set i to < message.length instead of <= or we will get an index out of range error. Here is your output from executing the code:

message
Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27