Solidity – Strings

Solidity - Strings

This topic is about Solidity – Strings.

Solidity supports String literal using both double quote (“) and single quote (‘). It provides string as a data type to declare a variable of type String.

pragma solidity ^0.5.0;

contract SolidityTest {
   string data = "test";
}

In above example, “test” is a string literal and data is a string variable. More preferred way is to use byte types instead of String as string operation requires more gas as compared to byte operation. Solidity provides inbuilt conversion between bytes to string and vice versa. In Solidity we can assign String literal to a byte32 type variable easily. Solidity considers it as a byte32 literal.

pragma solidity ^0.5.0;

contract SolidityTest {
   bytes32 data = "test";
}

Escape Characters

Sr.No.Character & Description
1\nStarts a new line.
2\\Backslash
3\’Single Quote
4\”Double Quote
5\bBackspace
6\fForm Feed
7\rCarriage Return
8\tTab
9\vVertical Tab
10\xNNRepresents Hex value and inserts appropriate bytes.
11\uNNNNRepresents Unicode value and inserts UTF-8 sequence.

Bytes to String Conversion

Bytes can be converted to String using string() constructor.

bytes memory bstr = new bytes(10);
string message = string(bstr);   

Example

Try the following code to understand how the string works in Solidity.

pragma solidity ^0.5.0;

contract SolidityTest {   
   constructor() public{       
   }
   function getResult() public view returns(string memory){
      uint a = 1; 
      uint b = 2;
      uint result = a + b;
      return integerToString(result); 
   }
   function integerToString(uint _i) internal pure 
      returns (string memory) {
      
      if (_i == 0) {
         return "0";
      }
      uint j = _i;
      uint len;
      
      while (j != 0) {
         len++;
         j /= 10;
      }
      bytes memory bstr = new bytes(len);
      uint k = len - 1;
      
      while (_i != 0) {
         bstr[k--] = byte(uint8(48 + _i % 10));
         _i /= 10;
      }
      return string(bstr);
   }
}

Run the above program using steps provided in Solidity First Application chapter.

Output

0: string: 3

In this topic we learn about Solidity – Strings. To know more, Click Here.

Leave a Reply