Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

* Programming 1 (BI)
  ◇ exercises
  ◇ quick link

teaching assets


Félévek

* 2024/25/2
* archívum


Linkek

* kalendárium
   - munkaszüneti napok '20
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C++
* C#
* Clojure
* D lang.
* Java
* Nim
* Scala


[ edit | logout ]
[ sandbox | passwd ]

Stringbuffer

Exercise: Write down the numbers from 1 to 15. The result must be a string.

(1) stringbuffer
def main():
    # naive way
    s = ""
    for i in range(1, 15 + 1):
        s = s + str(i)  # s += str(i)
    #
    print(s)  # 123456789101112131415

    # better way, with stringbuffer
    sb = []
    for i in range(1, 15 + 1):
        sb.append(str(i))
    #
    result = "".join(sb)
    print(result)  # 123456789101112131415
import std.stdio;
import std.conv;

void main()
{
    // naive way
    string s = "";
    foreach (i; 1 .. 15 + 1)
    {
        s = s ~ i.to!string;  // s ~= i.to!string;
    }
    writeln(s); // 123456789101112131415

    // better way, with stringbuffer
    char[] sb;
    foreach (i; 1 .. 15 + 1)
    {
        sb ~= i.to!string.dup;
    }
    string result = sb.idup;
    writeln(result); // 123456789101112131415
}

Notes:

  • Strings are immutable. When you concatenate two strings, the result is a new string object (naive way).
  • In D, if you need a mutable "string", you can use a char[] for that purpose. It's a list of characters, and a list can grow in size. You can append elements to it.
  • dup() returns a mutable copy, in this case a char[] .
  • idup() returns an immuable copy, in this case a string .
  • If you have a string, you can convert it to char[] with dup().
  • If you have a char[], you can convert it to a string with idup().
Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2025 July 02, 10:41