Skip to content

Instantly share code, notes, and snippets.

@jigar23
Created June 4, 2018 16:08
Show Gist options
  • Save jigar23/4c361745f4094716c4ccedf283d1154c to your computer and use it in GitHub Desktop.
Save jigar23/4c361745f4094716c4ccedf283d1154c to your computer and use it in GitHub Desktop.
Created using remix-ide: Realtime Ethereum Contract Compiler and Runtime. Load this file by pasting this gists URL or ID at https://remix.ethereum.org/#version=soljson-v0.4.23+commit.124ca40d.js&optimize=false&gist=
pragma solidity ^0.4.0;
library Strings {
function concat(string _base, string _value) internal
returns(string)
{
// By default, the type is storage but the value returned by bytes()
// is a memory pointer so explicitely mention that
// In order to modify string, you need to convert it to bytes
// string stores the UTF-8 format which can have > 1 byte
// bytes stores the raw byte format, where 2nd byte need not mean
// the 2nd character and its length need not mean the number of characters
//
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length);
bytes memory _newValue = bytes(_tmpValue);
uint i;
uint j;
for (i = 0; i < _baseBytes.length; i++) {
_newValue[j++] = _baseBytes[i];
}
for (i = 0; i < _valueBytes.length; i++) {
_newValue[j++] = _valueBytes[i];
}
return string(_newValue);
}
function strpos(string _base, string _value) internal
returns (int)
{
bytes memory _baseBytes = bytes(_base);
bytes memory _valueBytes = bytes(_value);
assert(_valueBytes.length == 1);
for (uint i = 0; i < _baseBytes.length; i++) {
if (_baseBytes[i] == _valueBytes[0]) {
return int(i);
}
}
return -1;
}
}
contract TestStrings {
using Strings for string;
function testConcat(string _base) public returns (string) {
return _base.concat("_suffix");
}
function testStrPos(string _base, string _value) public returns (int) {
return _base.strpos(_value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment