Why does STRSPLIT, contradictory to the documentation, need escaped backslashes in delimiter-specification?
    6 views (last 30 days)
  
       Show older comments
    
    Frederick Zittrell
      
 on 20 Feb 2018
  
    
    
    
    
    Commented: Stephen23
      
      
 on 6 Nov 2018
            According to the documentation, STRSPLIT is supposed to work like this:
C = strsplit('a\nb','\n')
C =
1×2 cell array
  'a'    'b'
However, I get
C =
cell
  'a\nb'
and
C = strsplit('a\nb','\\n')
C =
1×2 cell array
  'a'    'b'
Why does the backslash need to be escaped? Is this an error in the code or in the documentation, or am I missing something? I use MATLAB R2017a.
I am aware of SPLIT, which works as described in the documentation and is perfectly applicable, but the recommendation over STRSPLIT is only noted in STRSPLIT's "Tips" section, which I discovered only after fiddling with STRSPLIT.
0 Comments
Accepted Answer
  Suraj Mankulangara
      
 on 23 Feb 2018
        Hello Frederick
The character '\n' is not generally treated as a newline character by MATLAB, unless it is along with certain functions such as sprintf, fprintf etc. Instead, MATLAB treats '\n' as a string. This behaviour should be evident from the following code:
c = 'a\nb'
c =
      'a\nb'
If '\n' were treated as a newline character, the output would have been:
    'a
     b'
The 'strsplit' function treats '\n' as a newline character when used as part of the delimiter, whereas the 'split' function does not.
To specify newline characters, it is recommended that the newline function be used (starting from R2016b):
c = ['a' newline 'b']
c =
      'a
       b'
strsplit(c)
ans =
    1×2 cell array
      {'a'}    {'b'}
Alternatively, you can use char(10) to specify the actual ASCII character associated with a new line.
More Answers (0)
See Also
Categories
				Find more on Cell Arrays in Help Center and File Exchange
			
	Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!