Răsfoiți Sursa

add `lower` and `upper` for `str`

blueloveTH 2 ani în urmă
părinte
comite
712450f881
2 a modificat fișierele cu 22 adăugiri și 0 ștergeri
  1. 10 0
      src/pocketpy.h
  2. 12 0
      src/str.h

+ 10 - 0
src/pocketpy.h

@@ -487,6 +487,16 @@ inline void init_builtins(VM* _vm) {
         return VAR(Str(p));
     });
 
+    _vm->bind_method<0>("str", "lower", [](VM* vm, ArgsView args) {
+        const Str& self = _CAST(Str&, args[0]);
+        return VAR(self.lower());
+    });
+
+    _vm->bind_method<0>("str", "upper", [](VM* vm, ArgsView args) {
+        const Str& self = _CAST(Str&, args[0]);
+        return VAR(self.upper());
+    });
+
     /************ list ************/
     _vm->bind_constructor<2>("list", [](VM* vm, ArgsView args) {
         return vm->py_list(args[1]);

+ 12 - 0
src/str.h

@@ -210,6 +210,18 @@ struct Str{
         return Str(copy);
     }
 
+    Str lower() const{
+        std::string copy(data, size);
+        std::transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c){ return std::tolower(c); });
+        return Str(copy);
+    }
+
+    Str upper() const{
+        std::string copy(data, size);
+        std::transform(copy.begin(), copy.end(), copy.begin(), [](unsigned char c){ return std::toupper(c); });
+        return Str(copy);
+    }
+
     Str escape(bool single_quote=true) const {
         std::stringstream ss;
         ss << (single_quote ? '\'' : '"');