Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw Strings , how are these different from escaped strings and where should be use these

As per my research,

Kotlin has two types of string literals:-

Escaped strings that may have escaped characters in them .

val s = "Hello ,World\n" +
    "from escaped string\n"+
    "kotlin"

Raw string is delimited by a triple quote ("""), contains no escaping and can contain newlines and any other characters:

val m = """Hello, World
       |from raw string
       |kotlin """.trimMargin()

These strings can be used in multi lines without the need to concatenate each line and an without escaping.

Do we use raw strings only for simplicity and easy implementation or do these offer some better performance in any case?

And are these any other use-cases where we should consider using raw strings?

like image 835
Kaveri Avatar asked Sep 20 '18 06:09

Kaveri


People also ask

What's the difference between a raw string and escaped string?

Escaped string is declared within double quote (" ") and may contain escape characters like '\n', '\t', '\b' etc. Raw string is declared within triple quote (""" """) and may contain multiple lines of text without any escape characters.

What are raw strings used for?

Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.

What is a raw string and an escape sequence?

Raw string literals are string literals that are designed to make it easier to include nested characters like quotation marks and backslashes that normally have meanings as delimiters and escape sequence starts. They're useful for, say, encoding text like HTML.

What are escaped strings?

What is "Escaping strings"? Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes: "Hello, World."


1 Answers

Your answer is well explained here at this website. I am going to include only essential part of it here.

String in Kotlin can be used in multiple ways as described in the above link. It is purely depends upon the requirement for which to use. If you have extra large string like html page etc then you can go with Raw string delimited by triple quote ("""). And in where you have short strings then you could use Escaped strings.

There is no real performance difference between these but depends upon how much string concatenation you are using while building values in it.

like image 200
Rahul Khurana Avatar answered Oct 11 '22 05:10

Rahul Khurana