Skip to content

Commit 757688f

Browse files
author
setzeus
authored
Strings experimenting
Custom string libraries, practicing string manipulation
1 parent 68d958e commit 757688f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Strings.sol

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
pragma solidity ^0.4.9;
2+
3+
library Strings {
4+
function concact(string _base, string _value) internal returns(string) {
5+
bytes memory _baseBytes = bytes(_base);
6+
bytes memory _valueBytes = bytes(_value);
7+
8+
string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length);
9+
bytes memory _newValue = bytes(_tmpValue);
10+
11+
uint i;
12+
uint j;
13+
for(i=0;i<_baseBytes.length;i++) {
14+
_newValue[j++] = _baseBytes[i];
15+
}
16+
for(i=0;i<_valueBytes.length;i++) {
17+
_newValue[j++] = _valueBytes[i];
18+
}
19+
20+
return string(_newValue);
21+
22+
}
23+
24+
function strpos(string _base, string _value) internal returns (int) {
25+
bytes memory _baseBytes = bytes(_base);
26+
bytes memory _valueBytes = bytes(_value);
27+
28+
assert(_valueBytes.length == 1);
29+
30+
for(uint i=0;i<_baseBytes.length;i++) {
31+
if(_baseBytes[i] == _valueBytes[0]) {
32+
return int(i);
33+
}
34+
}
35+
36+
return -1;
37+
}
38+
}
39+
40+
contract testString {
41+
using Strings for string;
42+
43+
function testConcact(string _base) returns (string) {
44+
return _base.concact("_suffix");
45+
}
46+
47+
function needleInHaystack(string _base) returns (int) {
48+
return _base.strpos("t");
49+
}
50+
}

0 commit comments

Comments
 (0)