How do I reverse a String in Dart?

前端 未结 7 767
面向向阳花
面向向阳花 2021-02-03 20:13

I have a String, and I would like to reverse it. For example, I am writing an AngularDart filter that reverses a string. It\'s just for demonstration purposes, but it made me wo

7条回答
  •  庸人自扰
    2021-02-03 20:48

    Try this function

    String reverse(String s) {
      var chars = s.splitChars();
      var len   = s.length - 1;
      var i     = 0;
    
      while (i < len) {
        var tmp = chars[i];
        chars[i] = chars[len];
        chars[len] = tmp;
        i++;
        len--;
      }
    
      return Strings.concatAll(chars);
    }
    
    void main() {
      var s = "Hello , world";
      print(s);
      print(reverse(s));
    }
    

    (or)

    String reverse(String s) {
      StringBuffer sb=new StringBuffer();
      for(int i=s.length-1;i>=0;i--) {
        sb.add(s[i]);
      }
      return sb.toString();
    }
    
    main() {
      print(reverse('Hello , world'));
    }
    

提交回复
热议问题