-4
String str1 = "hello world";
String str2;
for (int i=0; i<str1.length(); i++)
{
    str2 = str2 + str1[i];
}

how do I push back elements of str1 in str2 sequencially?

SysDragon
  • 9,692
  • 15
  • 60
  • 89

5 Answers5

4

Don't forget to initialize String str2 = ""; . After that, do this inside the loop:

str2 = str2 + str1.charAt(i);

Or equivalently:

str2 += str1.charAt(i);

Either way, the trick is using the charAt() method for accessing a character at a given position.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
3

Instead of str1[i] use str1.charAt(i).

for (int i=0; i<str1.length(); i++)
{
str2 = str2 + str1.charAt(i);
}
2

Strings are immutable.... cannot be changed after adding them.... you cannot change them, but you can create new ones with the result you want.

Typically, you should use StringBuilder to do the manipulation, and the toString() at the end to get a final String result.

rolfl
  • 17,539
  • 7
  • 42
  • 76
0
String str1 = "hello world";
String str2 = "";
for (int i=0; i<str1.length(); i++)
{
    str2 = str2 + str1.charAt(i);
}

If you need to push the contents as a Stack, i.e. reverse the String.

String str1 = "hello world";
String str2 = "";
for (int i=str1.length()-1; i>-1; i--)
{
    str2 = str2 + str1.charAt(i);
}
System.out.println(str2);
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

You should look at the answers to the following questions.

Community
  • 1
  • 1
Sam Harwell
  • 97,721
  • 20
  • 209
  • 280