English 中文(简体)
Solidity - Strings
  • 时间:2025-02-21

Sopdity - Strings


Previous Page Next Page  

Sopdity supports String pteral using both double quote (") and single quote ( ). It provides string as a data type to declare a variable of type String.

pragma sopdity ^0.5.0;

contract SopdityTest {
   string data = "test";
}

In above example, "test" is a string pteral 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. Sopdity provides inbuilt conversion between bytes to string and vice versa. In Sopdity we can assign String pteral to a byte32 type variable easily. Sopdity considers it as a byte32 pteral.

pragma sopdity ^0.5.0;

contract SopdityTest {
   bytes32 data = "test";
}

Escape Characters

Sr.No. Character & Description
1

Starts a new pne.

2

\

Backslash

3

Single Quote

4

"

Double Quote

5



Backspace

6

f

Form Feed

7

Carriage Return

8

Tab

9

v

Vertical Tab

10

xNN

Represents Hex value and inserts appropriate bytes.

11

uNNNN

Represents 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 Sopdity.

pragma sopdity ^0.5.0;

contract SopdityTest {   
   constructor() pubpc{       
   }
   function getResult() pubpc 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 Sopdity First Apppcation chapter.

Output

0: string: 3
Advertisements