string 从matlab中的字符串中提取前4个字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5545963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:03:31  来源:igfitidea点击:

extract first 4 letters from a string in matlab

matlabstring

提问by Dilip

How can I extract the first 4 or the middle 4 or last four letters of a string example: when the string reads 01 ED 01 F9 81 C6?

如何提取字符串示例的前 4 个或中间 4 个或后四个字母:当字符串读取 01 ED 01 F9 81 C6 时?

回答by trolle3000

A string is treated like a vector of chars. Try this:

字符串被视为字符向量。尝试这个:

>> string = '01 ED 01 F9 81 C6'; 
>> string(1:5), string(6:11), string(12:17)

ans =
01 ED

ans =
 01 F9

ans =
 81 C6

stringin this example is a variable not a method. string(1)returns the first char in the array (or vector) called string.

string在这个例子中是一个变量而不是一个方法。string(1)返回名为 的数组(或向量)中的第一个字符string

回答by b3.

If you want only the non-whitespace characters you could use the ISSPACEfunction to remove the whitespace and then character array indexing to access the characters:

如果您只想要非空白字符,则可以使用ISSPACE函数删除空白,然后使用字符数组索引来访问字符:

>> s = '01 ED 01 F9 81 C6';
>> s = s(~isspace(s))

s =

01ED01F981C6

>> s(1:4)

ans =

01ED

>> s(5:8)

ans =

01F9

>> s(9:end)

ans =

81C6

You can expand this to process multiple lines of a character array using RESHAPEto transform the result of the space removal back to a 2D-array and then referencing the extra dimension:

您可以将其扩展为使用RESHAPE处理字符数组的多行,将空间移除的结果转换回二维数组,然后引用额外的维度:

 s = ['01 ED 01 F9 81 C6'; 'F8 CA DD 04 44 3B']

s =

01 ED 01 F9 81 C6
F8 CA DD 04 44 3B

>> s = reshape(s(~isspace(s)), size(s, 1), 12)

s =

01ED01F981C6
F8CADD04443B

>> s(:,1:4)

ans =

01ED
F8CA

>> s(:,5:8)

ans =

01F9
DD04

>> s(:,9:end)

ans =

81C6
443B

回答by Richie Cotton

As trolle3000 and b3 mentioned, you use brackets containing indices to extract subsets of the string.

正如 trolle3000 和 b3 所提到的,您使用包含索引的括号来提取字符串的子集。

To answer the additional question of how you work on the string, I suggest that you split the string at each space, and convert from hexadecimal to decimal numbers.

要回答有关如何处理字符串的附加问题,我建议您在每个空格处拆分字符串,然后将十六进制数转换为十进制数。

s = '01 ED 01 F9 81 C6';
hex2dec(regexp(s, ' ', 'split'))

ans =   
     1
   237
     1
   249
   129
   198