字符串的表示

在MATLAB中,字符串使用单引号括起来的字符序列

  1. >> xm = 'Haibin Institute of Technology'
  2. xm =
  3. 'Haibin Institute of Technology'
  4. >> xm(1:3)
  5. ans =
  6. 'Hai'

若字符串中的字符含有单引号,则需要用一个单引号作为转义字符

  1. >> 'I''m a student'
  2. ans =
  3. 'I'm a student'

也可以建立字符串矩阵

  • 注意,数组中字符串的长度要相同
    1. >> ch = ['abcde'; 'hsadf']
    2. ch =
    3. 2×5 char 数组
    4. 'abcde'
    5. 'hsadf'
    image.png
    1. >> ch = 'ABc123d4e45Fg9';
    2. >> subch = ch(1:5)
    3. subch =
    4. 'ABc12'
    5. >> revch = ch(end:-1:1)
    6. revch =
    7. '9gF54e4d321cBA'
    8. >> k = find(ch>='a' & ch<='z')
    9. k =
    10. 3 7 9 13
    11. >> ch(k) = ch(k) - ('a'-'A')
    12. ch =
    13. 'ABC123D4E45FG9'
    14. >> length(k)
    15. ans =
    16. 4

    字符串的操作

  1. 字符串的执行 eval(s)

    1. >> t = pi;
    2. >> m = '[t, sin(t), cos(t)]';
    3. >> y = eval(m)
    4. y =
    5. 3.1416 0.0000 -1.0000
  2. 字符串与数值之间的转换

image.png

  1. >> s1 = 'MATLAB';
  2. >> a = abs(s1)
  3. a =
  4. 77 65 84 76 65 66
  5. >> char(a+32)
  6. ans =
  7. 'matlab'
  1. 字符串的比较

image.png

  1. >> char(a+32)
  2. ans =
  3. 'matlab'
  4. >> 'www0' >= 'W123'
  5. ans =
  6. 1×4 logical 数组
  7. 1 1 1 0

image.png

  1. >> strcmp('www0', 'w123')
  2. ans =
  3. logical
  4. 0
  5. >> strncmpi('Www0', 'w123', 1)
  6. ans =
  7. logical
  8. 1
  1. 字符串的查找和替换

image.png

  1. >> p = findstr('This is a test!', 'is')
  2. p =
  3. 3 6
  4. >> p = findstr('is', 'This is a test!')
  5. p =
  6. 3 6
  7. >> result = strrep('This is a test!', 'test', 'class')
  8. result =
  9. 'This is a class!'