"Phone Book Contract" Example
In this example ive learned the following concepts.
The use of a loop
The use of an if conditional statement
The Creator of the contract is the same as the account holding Ether
String comparison requires utility functions.
You can also use the "import" keyword to import external solidity contracts. but i kept getting errors on Remix.
Basic usage for "import"
import "github.com/Arachnid/solidity-stringutils/strings.sol";
pragma solidity ^0.4.0;
contract PhoneBookAresh{
//Declare a struct similar to C++
struct Person{
string fullName;
string number;
}
//An Array of structs similar to C++ (flexible storage) and index start at 0
Person[] MyPhoneBook;
//whos phonebook it is. The Value is the Hex value of the account
address creator;
//this is a constructor, notice it has the same name as the Contract name
function PhoneBookAresh() public {
creator = msg.sender;
}
//Adds an item to the Phonebook using PUSH
function AddPhone(string _fullName, string _number) public
{
MyPhoneBook.push(Person(_fullName,_number));
}
function GetPerson(uint _index) constant returns (string)
{
return MyPhoneBook[_index].fullName;
}
function GetPhoneNumber(string _fullName) constant returns (string)
{
uint PhoneBookLength = MyPhoneBook.length;
//Must be uint and not int
for (uint i=0; i< PhoneBookLength; i++)
{
//As in Java, the == operator does not compare the literals of two strings.
if (stringsEqual(MyPhoneBook[i].fullName,_fullName))
{
return MyPhoneBook[i].number;
}
}
}
//Manually comparing strings function used as a utility function
//source https://github.com/ethereum/dapp-bin/blob/master/library/stringUtils.sol
function stringsEqual(string storage _a, string memory _b) internal returns (bool) {
bytes storage a = bytes(_a);
bytes memory b = bytes(_b);
if (a.length != b.length)
return false;
// @todo unroll this loop
for (uint i = 0; i < a.length; i ++)
if (a[i] != b[i])
return false;
return true;
}
}
Comments
Post a Comment