Add Method to String Class

Add method to string class

You can extend the String prototype;

String.prototype.distance = function (char) {
var index = this.indexOf(char);

if (index === -1) {
alert(char + " does not appear in " + this);
} else {
alert(char + " is " + (this.length - index) + " characters from the end of the string!");
}
};

... and use it like this;

"Hello".distance("H");

See a JSFiddle here.

Can I add new methods to the String class in Java?

String is a final class which means it cannot be extended to work on your own implementation.

Add method .equalsOr() to String class

If you want to check equality of your string1 to a set of strings string2, string3, string4, string5. It's better to use any collection (i.e. Set or List). For example, if you use

 Arrays.asList(string2, string3, string4, string5).contains(string1)

it will give you the espected result.

Add custom method to string object

You can't because the builtin-types are coded in C. What you can do is subclass the type:

class string(str):
def sayHello(self):
print(self, "is saying 'hello'")

Test:

>>> x = string("test")
>>> x
'test'
>>> x.sayHello()
test is saying 'hello'

You could also overwrite the str-type with class str(str):, but that doesn't mean you can use the literal "test", because it is linking to the builtin str.

>>> x = "hello"
>>> x.sayHello()
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
x.sayHello()
AttributeError: 'str' object has no attribute 'sayHello'
>>> x = str("hello")
>>> x.sayHello()
hello is saying 'hello'

Javascript adding methods to String instance

Strings and numbers are autoboxed primitives, meaning that when you perform OO operations on them, they are cast as "String" and "Number" classes but then are immediately unboxed.

Your code evaluates to:

x = "123"
(new String(x)).method = function() { console.log("test") }

(new String(x)).method() // Error

Your second call is failing because you are dealing with an entirely different String object. As T.J. stated, you can get around this by making x a String object, but this is not a common or recommended practice.

You can extend all strings by adding the method to String.prototype:

x = "123"
String.prototype.method = function() { console.log("test") }

x.method()

This call evaluates the same way as (new String(x)).method() but since that method exists in the prototype, it will get called.

Adding function to string class

Be sure you declare your function in public section of class.

Maybe you would love composition over inheritance ;)

    class MyString
{
std::string m_string; // do not inherit just composition it
public:
explicit MyString(const std::string& str)
: m_string(str)
{
}

// your function should be in public scope I think
MyString& add(const std::string& begin, const std::string& end)
{
m_string.insert(0, begin);
m_string.append(end);
return *this;
}

const std::string& string() const
{
return m_string;
}
};

class Parent
{
MyString m_string;
public:
void surround(const std::string& begin, const std::string& end)
{
m_string.add(begin, end);
}
};

int main(int argc, char *argv[])
{
std::cout << MyString("inherit").add("Do not ", " from std::string!").string() << std::endl;
return 0;
}

How can I add a method to a string, using it's prototype when it is immutable?

String in Javascript is immutable, it is a true statement. So, you are correct.
So, the value of the string is immutable but not it's prototype. String inherited the prototype from its parent object. The functions available in the prototype do not modify the value of string, it returns a new instance of string.

When it comes to inheritance, JavaScript only has one construct:
objects. Each object has a private property which holds a link to
another object called its prototype. That prototype object has a
prototype of its own, and so on until an object is reached with null
as its prototype. By definition, null has no prototype, and acts as
the final link in this prototype chain.

The value of string in javascript is loosely coupled with prototype. If you replace the prototype of string with empty object, there will be no change of the value. You will get the exactly same value for the string when you will access it.



Related Topics



Leave a reply



Submit