Literals/String: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
(Added Rust example) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(2 intermediate revisions by 2 users not shown) | |||
Line 2,567:
let string_slice_str2: &str = "hello str"; // String slice pointing to string literal "hello str"
let string1: String =
let string2: String = String::from("
let string3: String = "
let string4: String = "bye".to_owned();
let string5: String = "see you soon".into();
// The "to_string()", "to_owned" or "into" are all equivalent in the code above.
// The "to_string()", "to_owned" or "into" methods are needed so that a string slice (&str) or a string literal (&str) is explicitly converted into a heap-allocated fully-owned String type. Otherwise the compiler's type checker will complain "expected struct `String`, found `&str` (string slice)"
let
// String slices can also point to heap allocated strings:
let string_slice_str3: &str = &
let
</syntaxhighlight>
Line 3,117 ⟶ 3,119:
<syntaxhighlight lang="vbnet">Dim s = "Tom said, ""The fox ran away."""
Result: Tom said, "The fox ran away."</syntaxhighlight>
=={{header|V (Vlang)}}==
Character literals for Unicode characters, "rune literals", are an alias for u32.
Character literals for UTF-8 characters, "string literals", are an alias for u8.
To denote rune, Unicode characters, ` (backticks) are used :
A rune can be converted to a UTF-8 string by using the .str() method.
rocket := `🚀`
rocket.str() == '🚀' // uses single quotes, not the backtick, after conversion
A string can be converted back to runes by the .runes() method.
hello := 'Hello World'
hello_runes := hello.runes() // [`H`, `e`, `l`, `l`, `o`, ` `, `W`, `o`, `r`, `l`, `d`]
In V, a string is an immutable array of read-only bytes. All Unicode characters are encoded using UTF-8:
mut s := 'hello 🌎'
s[0] = `H` // not allowed as immutable
// convert `string` to `[]u8`
s := 'hello 🌎'
arr := s.bytes()
assert arr.len == 10
// convert `[]u8` to `string`
s2 := arr.bytestr()
assert s2 == s
// indexing gives a byte, u8(66) == `B`
name := 'Bob'
println(name.len == 3) // will print 3
if name[0] == u8(66) {println(name[0].ascii_str())} // will print`B`
String literals are contained in quotes:
str:= "Hello, world!"
=={{header|WEB}}==
Line 3,169 ⟶ 3,223:
From v0.4.0 Wren also supports ''raw'' string literals. These are any text surrounded by triple double quotes, """, and are interpreted verbatim i.e. any control codes and/or interpolations are not processed as such. They can include single or double double quotes without problem.
<syntaxhighlight lang="
var t = "abc\t123\%"
var u = "\U0001F64A\U0001F680"
|