Reading a select number of characters from a string

조회 수: 1,443 (최근 30일)
Louis . 2011년 12월 25일
댓글: Kiana Maillet . 2022년 8월 15일
How would I go about taking the first 5 characters of a string? I want to be able to take a string like "some_string" and take the first 5 characters so I get a new string "some_". I am not sure where to look in MatLab documentation for this.
  댓글 수: 4
Johann Alban Schöpfer
Johann Alban Schöpfer 2018년 1월 26일
If you are reading this in the glorious time of the string data type, you can use the answers below by going back to a char array.
str = "I want to edit this string";
temp = char(str);
% do the things
str = string(temp);

댓글을 달려면 로그인하십시오.

답변 (5개)

Junaid 2011년 12월 25일
Dear Louis,
Let say you have string Variable a;
a = 'HelloMoto';
if you want to take first 5 character of this. It is straight forward.
b = a(1:5); % now b has a's first characters only.
Similarly if you have array of String like this;
A = {'String1', 'String2','String3' };
Then taking string2 as your "Some_String" and then take first 5 character would be like this.
B = A{2};
I hope this is what you asked for ? Do let me know in either case.
  댓글 수: 4
Kiana Maillet
Kiana Maillet 2022년 8월 15일
Isn't 'that' a character array? and "this" would be a string..

댓글을 달려면 로그인하십시오.

Jurgen 2019년 12월 16일
If you don't want to convert to char type: extractBetween and it's brethren work on the newer string datatype.

Junaid 2011년 12월 25일
Dear Let say your file name is "someFile.xls" then following code should work.
[m mess] = xlsread('someFile.xls', 1);
The size of mess with be number columns and rows in sheet one. Lets assume that in first row second colum there is your requires string you want to take first three initial characters. Then this code should work.
a = char(mess(1,2)); % now a contains that string
myStr = a(1:3); % this should return your first three characters.
Try and let us know, if it works. For experiments you make your own xls file so that you put the string you want. Once the code works and give desired resutls then it would be easy for you to debug your problem in your current xls file, as you mentioned due to spaces or anything.
  댓글 수: 3
Jan 2011년 12월 25일
@Louis: The white space characters do not cause troubles, because they are characters. But if the strings have less than 3 characters, "a(1:3)" will fail.

댓글을 달려면 로그인하십시오.

Jan 2011년 12월 25일
This crops the first 3 characters, but dos not touch shorter strings:
[~,message] = xlsread('someFile.xlsx', 1, entryF);
a = message(1:min(3, length(a)));
  댓글 수: 3
word= char('cacabcabac');

댓글을 달려면 로그인하십시오.

Vahidreza Jahanmard
Vahidreza Jahanmard 2022년 3월 25일
If you have string format (not char format), you can use this function:


Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by