1

I have a function where one of its arguments is a string. How would I check the string for leading and trailing whitespaces and remove those characters?

If i get something like this:

"    " => ""

or

"     foo" => "foo"

or

"foo     " => "foo"

In PHP I can use the method trim and it returns the string with whitespaces stripped from the beginning and end.

I did not find any solution on StackExchange.

How do I do a trim in solidity?

2

Unless there is a very solid argument, I would suggest setting this concern aside. The main reasons.

  1. clients can and should send valid inputs
  2. Immutable contracts can and should be as simple as possible as a first line of defense against defects, so don't load them up with concerns that clients can and should attend to.
  3. Whatever processing happens in the contract will cost gas. With few exceptions, economics requires that clients with (essentially) free and plentiful processing power should be subordinate to the contract's preferred types and input requirements which are optimized for performance, readability and reliability.
  4. Usually, string is a terrible type for anything associated with application integrity. Sometimes it makes sense to store such things on chain in the interest of minimizing complexity. They are frequently candidates for off-chain storage because they are of no importance to contract logic.

TL;DR;

Garbage in, garbage out is a good policy for a contract.

Hope it helps.

  • Hi, thanks for you answer. You right, everyone should handle data on client side and send it, but someone can call my contracts methods and send wrong data. For example i have online game and i want to create some rating module. There are a lot of user names and someone created empty user name, and it'll looks like a bug. And i would like to avoid it. I know, it can take some commission but still it's very interesting task. – Станислав Тепляков May 23 at 7:47
  • 1
    A second thing to think about would input validation. Maybe check if the first byte is a space and revert. I would also challenge the use of usernames in Ethereum. This whole issue can be avoided if the system doesn't do that. Legacy systems can be extended to associate ethereum addresses with user profiles if you need to. – Rob Hitchens - B9lab May 23 at 14:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.