Skip to content

Instantly share code, notes, and snippets.

Embed
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
else:
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
else:
self.string += string
def clear(self):
self.string = ""
# Usage
sb = StringBuilder()
sb.append("Hello, ")
sb.append("World!")
assert sb.toString() == "Hello, World!"
sj = StringJoiner(", ")
sj.append("a")
sj.append("b")
sj.append("c")
assert sj.toString() == "a, b, c"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment