如何在for循环的每次迭代中更新字符串?

时间:2017-03-24 11:25:01

标签: java

   String up="hello world";
    String end;
    String w;

    for(int i=0;i<up.length();i++){
      n=0;
        z=3;
        end="hello world";
        w=end.substring(n,z);

        end=end.replace(w,"");
        System.out.println(end);
    }
    System.out.println("-->");

这里我有这个字符串,我只想用“”替换字符串中的每个字母,并在循环结束时更新替换的字符串 例如: 最初我们在第一次迭代后得到了“hello world”我希望它成为up =“ello world”

3 个答案:

答案 0 :(得分:0)

你可以尝试一些简单的事情:

foreach ($table as $t) {
    if (in_array($t->id_f, $array){
     // do something
     } else {
     // do something else
     }
 }

请务必前往https://msdn.microsoft.com/library/system.string(v=vs.110).aspx并了解String类的所有方法和参数如何工作。

答案 1 :(得分:0)

您的代码的主要问题是您为每次迭代分配end="hello world";,因此每次都会重置end

这样做的一种方式是:

String up = "hello world";

while (!up.isEmpty()) {
  up = up.substring(1);
  System.out.println(up);
}

答案 2 :(得分:0)

您可以使用char Array

执行此操作
public class MultipleTry {

public static void main(String args[]){

    char c = '\0';
    String up="hello world";

    char[] charArray = up.toCharArray();


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

        charArray[i] = c;
        up = new String(charArray);
        System.out.println(up);
    }       
 }

}

如果您对贝娄线有疑问,

  

char c ='\ 0';

click来获取更多信息