Skip to content

Instantly share code, notes, and snippets.

Last active April 12, 2022 00:30
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Emulates Java's StringBuilder and StringJoiner, sort of.
class StringBuilder:
Works like Java's StringBuilder
def __init__(self, initial_string=None):
if initial_string is not None:
self.string = initial_string
self.string = ""
def append(self, string):
self.string += string
def toString(self):
return self.string
def clear(self):
self.string = ""
class StringJoiner(StringBuilder):
Works like Java's StringJoiner
def __init__(self, delimiter):
self.delimiter = delimiter
super(StringJoiner, self).__init__()
def append(self, string):
if self.string != "":
self.string += self.delimiter + string
self.string += string
def clear(self):
self.string = ""
# Usage
sb = StringBuilder()
sb.append("Hello, ")
assert sb.toString() == "Hello, World!"
sj = StringJoiner(", ")
assert sj.toString() == "a, b, c"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment