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

 

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE