【Tcl学习笔记】第5章 字符串操作

本文介绍Tcl语言中字符串处理的方法,包括字符取值、长度计算、大小写转换、字符串搜索与比较、格式化创建字符串、正则表达式匹配与替换等功能,并详细解释了各种命令的使用方法。

5.2 取字符:string index 和 string range

string index "hello world" 0
输出:h
string range "hello world" 6 end-1
输出:worl

  • 索引从0开始
  • end对应结尾
  • 可以使用表达式,如end-$i

5.3 长度、大小写转换、裁剪、重复

  1. 长度:string length "hello world"
    输出:11
  2. 大小写转换:string toupper "Hello World"(小写:string tolower)
    输出:HELLO WORLD
  3. 裁剪
    • 匹配两端:string trim "abcxxxcba" ab
      输出:cxxxc
    • 匹配左边:string trimleft "abcxxxcba" ab
      输出:cxxxcba
    • 匹配右边:string trimright "abcxxxcba" ab
      输出:abcxxxc
  4. 重复:string repeat "hello world" 2
    输出:hello worldhello world

5.4 简单搜索

从左到右搜索字符串中第一个wo的首字符位置,找不到返回-1:
string first wo "hello worldhello world"
输出:6
指定从索引为10的字符开始搜索:
string first wo "hello worldhello world" 10
输出:17
string last: 从右到左搜索

5.5 字符串比较

string compare "hello" "Hello"
输出:1
string compare "Hello" "hello"
输出:-1
string compare "Hello" "Hello"
输出:0
忽略大小写:string compare -nocase "Hello" "hello"
输出:0
设置比较的长度:string compare -length 1 "hELLO" "hello"
输出:0
只返回0(不相同)或1(相同):string equal -nocase -length 2 "hello" "Hexxx"
输出:1

5.6 字符串置换

  1. string replace
    string replace "hello world" 6 10 "Tcl"
    输出:hello Tcl
    • 参数 6 10被替换字符串索引的起始与结束。
    • 参数Tcl:可以省略,结果等效为删除。
  2. string map dictionary string
    将string中出现的的所有dictionary关键字置换为相应的值。
    set entities {
        action1 hello
        action2 learn
        name    Tcl
    }
    string map -nocase $entities {Action1 name,action2 name}
    </
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChipWeaver

觉得有用的话点个赞吧 :)

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值