DEV Community

Cover image for String Type and String Literals in Solidity
Shlok Kumar
Shlok Kumar

Posted on

String Type and String Literals in Solidity

Solidity supports both double quotation (") and single quote (') when referencing a string literal. It makes it possible to declare a variable of type String by providing the data type string.

pragma solidity ^0.5.0;

contract SolidityTest {
   string data = "test";
} 
Enter fullscreen mode Exit fullscreen mode

In the above example, the string literal "test" is represented by the string variable data. Because string operations use more gas than byte operations, it is preferable to employ byte types rather than String operations wherever possible instead of String operations. Solidity includes built-in conversion between bytes and strings, as well as the other way around. In Solidity, we can quickly and efficiently assign a String literal to a byte32 type variable. Solidity treats it as if it were a byte32 literal.

pragma solidity ^0.5.0;

contract SolidityTest {
   bytes32 data = "test";
} 
Enter fullscreen mode Exit fullscreen mode

Additionally, string literals also support the following escape characters:

  • <newline> (escapes an actual newline)

  • \ (backslash)

  • \' (single quote)

  • \" (double quote)

  • \n (newline)

  • \r (carriage return)

  • \t (tab)

  • \xNN (hex escape)

  • \uNNNN (Unicode escape)

For more content, follow me on - https://linktr.ee/shlokkumar2303

 

Top comments (0)