字符串 #
一、字符串基础 #
1.1 创建字符串 #
使用双引号创建字符串:
julia
s1 = "Hello, Julia!"
s2 = "你好,世界!"
s3 = ""
1.2 多行字符串 #
使用三引号创建多行字符串:
julia
s = """
这是一个
多行字符串
"""
1.3 原始字符串 #
使用raw前缀创建原始字符串:
julia
s = raw"C:\Users\name\file.txt"
1.4 字符串类型 #
julia
typeof("Hello")
typeof("你好")
二、字符 #
2.1 字符类型 #
使用单引号创建字符:
julia
c1 = 'A'
c2 = '中'
c3 = '\u2200'
typeof('A')
2.2 字符与字符串 #
julia
'A' == "A"
'A' === "A"
string('A')
first("Hello")
2.3 字符编码 #
julia
Int('A')
Int('中')
Char(65)
Char(20013)
codepoint('A')
2.4 字符分类 #
julia
isdigit('5')
isalpha('A')
isalnum('A')
islower('a')
isupper('A')
isspace(' ')
ispunct('!')
三、字符串索引 #
3.1 字节索引 #
Julia使用字节索引访问字符串:
julia
s = "Hello"
s[1]
s[5]
s[begin]
s[end]
3.2 Unicode索引 #
对于Unicode字符,需要使用正确的索引:
julia
s = "你好"
s[1]
length(s)
sizeof(s)
3.3 安全索引 #
使用nextind和prevind:
julia
s = "你好"
i = firstindex(s)
while i <= lastindex(s)
println(s[i])
global i = nextind(s, i)
end
3.4 eachindex #
使用eachindex遍历:
julia
s = "你好世界"
for i in eachindex(s)
println(i, " => ", s[i])
end
四、字符串切片 #
4.1 基本切片 #
julia
s = "Hello, Julia!"
s[1:5]
s[8:end]
s[begin:5]
s[1:2:end]
4.2 SubString #
切片返回SubString类型:
julia
s = "Hello, Julia!"
sub = s[1:5]
typeof(sub)
String(sub)
4.3 字符串视图 #
SubString是原字符串的视图,不复制数据:
julia
s = "Hello, Julia!"
sub = @view s[1:5]
五、字符串操作 #
5.1 连接 #
使用*连接字符串:
julia
"Hello" * ", " * "Julia"
使用string函数:
julia
string("Hello", ", ", "Julia")
string(1, 2, 3)
使用join:
julia
join(["Hello", "Julia"], ", ")
join([1, 2, 3], "-")
5.2 重复 #
使用^重复字符串:
julia
"Julia" ^ 3
repeat("Julia", 3)
5.3 分割 #
julia
split("Hello,Julia,World", ",")
split("Hello Julia World")
split("a,b;c:d", [',', ';', ':'])
5.4 替换 #
julia
replace("Hello, World!", "World" => "Julia")
replace("Hello, World!", "o" => "0")
replace("Hello, World!", 'o' => '0', count=1)
5.5 去除空白 #
julia
strip(" Hello ")
lstrip(" Hello ")
rstrip(" Hello ")
strip("\n\tHello\n\t")
5.6 大小写转换 #
julia
uppercase("hello")
lowercase("HELLO")
titlecase("hello world")
uppercasefirst("hello")
lowercasefirst("HELLO")
六、字符串搜索 #
6.1 查找子串 #
julia
s = "Hello, Julia!"
findfirst("Julia", s)
findfirst("l", s)
findlast("l", s)
findnext("l", s, 4)
findprev("l", s, 10)
6.2 检查包含 #
julia
s = "Hello, Julia!"
occursin("Julia", s)
occursin("World", s)
startswith(s, "Hello")
endswith(s, "!")
contains(s, "Julia")
6.3 计数 #
julia
s = "Hello, Julia!"
count('l', s)
count("l", s)
七、字符串插值 #
7.1 基本插值 #
使用$进行插值:
julia
name = "Julia"
println("Hello, $name!")
x = 10
y = 20
println("$x + $y = $(x + y)")
7.2 表达式插值 #
使用$(...)插入表达式:
julia
arr = [1, 2, 3]
println("Array: $arr, Sum: $(sum(arr))")
7.3 转义 #
julia
println("Dollar sign: \$")
println("Backslash: \\")
八、格式化字符串 #
8.1 Printf风格 #
julia
using Printf
@printf("Integer: %d\n", 42)
@printf("Float: %.2f\n", 3.14159)
@printf("String: %s\n", "Julia")
@printf("Width: %10d\n", 42)
@printf("Left: %-10d|\n", 42)
8.2 sprintf #
julia
using Printf
s = @sprintf("%.2f", 3.14159)
8.3 Format.jl #
julia
using Format
fmt"{} + {} = {}"(1, 2, 3)
fmt"{:.2f}"(3.14159)
九、正则表达式 #
9.1 创建正则表达式 #
julia
re = r"hello"
typeof(re)
9.2 匹配 #
julia
re = r"\d+"
occursin(re, "abc123def")
m = match(re, "abc123def")
m.match
m.offset
9.3 查找所有匹配 #
julia
re = r"\d+"
eachmatch(re, "abc123def456ghi789")
collect(eachmatch(re, "abc123def456ghi789"))
9.4 替换 #
julia
re = r"\d+"
replace("abc123def456", re => "NUM")
replace("abc123def456", re => s"NUM")
9.5 捕获组 #
julia
re = r"(\d+)-(\d+)"
m = match(re, "abc123-456def")
m[1]
m[2]
m.captures
9.6 正则表达式选项 #
julia
re = r"hello"i
occursin(re, "HELLO")
re = r"hello."s
match(re, "hello\nworld")
十、字符串比较 #
10.1 相等比较 #
julia
"hello" == "hello"
"hello" == "Hello"
"hello" === "hello"
10.2 字典序比较 #
julia
"abc" < "abd"
"abc" < "abcd"
"abc" < "ABC"
10.3 忽略大小写比较 #
julia
lowercase("Hello") == lowercase("hello")
casecmp("Hello", "hello")
十一、字符串与数字转换 #
11.1 字符串转数字 #
julia
parse(Int, "42")
parse(Float64, "3.14")
parse(Int, "FF", base=16)
tryparse(Int, "42")
tryparse(Int, "abc")
11.2 数字转字符串 #
julia
string(42)
string(3.14)
string(255, base=16)
string(255, base=2, pad=8)
十二、实践练习 #
12.1 练习1:字符串处理 #
julia
function word_count(text::String)
words = split(lowercase(text))
counts = Dict{String, Int}()
for word in words
w = strip(word, ['.', ',', '!', '?', ';', ':'])
counts[w] = get(counts, w, 0) + 1
end
return counts
end
text = "Hello, world! Hello, Julia!"
word_count(text)
12.2 练习2:回文检测 #
julia
function is_palindrome(s::String)
cleaned = lowercase(replace(s, r"\W" => ""))
return cleaned == reverse(cleaned)
end
is_palindrome("A man, a plan, a canal: Panama")
is_palindrome("Hello")
12.3 练习3:字符串格式化 #
julia
function format_table(headers::Vector{String}, rows::Vector{Vector{String}})
widths = [maximum(length.(col)) for col in zip(headers, eachrow(hcat(rows...))...)]
function format_row(row, widths)
join([lpad(cell, w) for (cell, w) in zip(row, widths)], " | ")
end
println(format_row(headers, widths))
println(join(["-"^w for w in widths], "-+-"))
for row in rows
println(format_row(row, widths))
end
end
headers = ["Name", "Age", "City"]
rows = [["Alice", "25", "New York"], ["Bob", "30", "Los Angeles"]]
format_table(headers, rows)
12.4 练习4:正则表达式 #
julia
function extract_emails(text::String)
re = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
[m.match for m in eachmatch(re, text)]
end
text = "Contact us at info@example.com or support@test.org"
extract_emails(text)
十三、总结 #
本章我们学习了:
- 字符串创建:双引号、多行字符串、原始字符串
- 字符类型:Char类型和字符操作
- 字符串索引:字节索引和Unicode索引
- 字符串切片:切片操作和SubString
- 字符串操作:连接、分割、替换、大小写
- 字符串搜索:查找和包含检查
- 字符串插值:$和$(…)语法
- 正则表达式:匹配、替换、捕获组
接下来让我们学习Julia的布尔类型和Nothing类型!
最后更新:2026-03-27