left characters of a string

90 views (last 30 days)
Danielle Leblanc
Danielle Leblanc on 6 Jul 2011
Answered: Steven Lord on 26 Nov 2022
if I have a name 'Microsoft', how can i get the first 6 characters 'Micros'?

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 6 Jul 2011
name = 'Microsoft'
out = name(1:6)
  2 Comments
Real User
Real User on 26 Nov 2022
Edited: Real User on 26 Nov 2022
What if name has < 6 characters?
Is there some short way or do have have to write
out = name(1:min(6,length(name)));
substr seems to require some stateflow package https://se.mathworks.com/help/stateflow/ref/substr.html
Stephen23
Stephen23 on 26 Nov 2022
name = 'Microsoft';
name(1:min(end,6))
ans = 'Micros'
name = 'Cat';
name(1:min(end,6))
ans = 'Cat'

Sign in to comment.

More Answers (1)

Steven Lord
Steven Lord on 26 Nov 2022
This wasn't an option when the question was originally asked, but the extractBefore function will work for both char vectors and string arrays.
c = 'Microsoft'
c = 'Microsoft'
c6 = extractBefore(c, 7)
c6 = 'Micros'
s = string(c)
s = "Microsoft"
s6 = extractBefore(s, 7)
s6 = "Micros"

Categories

Find more on Stateflow in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!