1

i have a file Text.txt with following sepecified content:

 !typ truck,bus,car,motor,bicycle 
 !end typ 
 !allowed car,motor,bicycle
 !end allowed

I want to get the string "car,motor,bicycle" from the row "!allowed car,motor,bicycle". So I did these in MATLAB 2012b:

io_contents = fullfile( 'Text.txt'); % open Textfile
Text = fileread( io_contents ); % read the content of io_contents
Rowbegin = strfind(Text,'!allowed'); %find the beginn of the row  in  Text
Rowend = strfind(Text,'!end allowed')-4 ;  %find the end of the row in Text
Row = Text(Rowbegin:Rowend) 
String = textscan(Row,'!allowed%s ');   
String = String{1}{1} 

it should work in Matlab 2012b,but in matlab 2013b it shows this message:

Caught "std::exception" Exception message is: invalid string position 

at line 6 , where TEXTSCAN used is.

Could you tell me the reason, and how could I solve it. Is the an alternativ functioin for the function textscan ? Thanks a lot

  • What's the intended purpose of line `String = textscan(Row,'!allowed%s ')`? If it's just to remove `!allowed` at the beginning of `Row`, why not just search for the second `!` and remove everything before that? – Luis Mendo Jan 01 '14 at 13:02
  • Can't reproduce the error. On R2013a, your code produces `Row =` `!allowed` `!car,motor,bicycl` `String =` `''`. What strange kind of text file format is that anyway? :-) – A. Donda Jan 01 '14 at 15:35
  • Please run the code with `dbstop if error` and see what the value is of `Row` at the time when the error occurs. – Dennis Jaheruddin Jan 02 '14 at 14:37
  • @LuisMendo I want to get the String "car,motor,bicycle" from the row "!allowed car,motor,bicycle" as you said, it is simply removing the group "!allowed" from the row. – Nguyễn Thanh Kim Jan 02 '14 at 14:42
  • @A.Dona sorry, there is a mistake in my Text. I corrected it. There schould be a "!" at the beginn of every row. – Nguyễn Thanh Kim Jan 02 '14 at 14:42
  • @DennisJaheruddin Thanks for your advice. I will try it. This error appears with my Tutors computer. He has Matlab 2013b. And it is very inconvinnient to apply changes quickly. With 2012b in my computer there is not any error :( – Nguyễn Thanh Kim Jan 02 '14 at 14:45

1 Answers1

1

Though I am not really convinced that this is related to the 2013b version, here is an alternate solution.

Replace the textscan line by this:

strrep(Row,'!allowed ','')

If you want to do more advanced things, you can look into regular expressions, but for matching a word in a string this is usually the easiest way. As a bonus it should be fairly efficient as well.


It may also be possible to skip a step if you don't need the intermediate result of Row. In that case use:

String = Text(Rowbegin+9:Rowend) 
Dennis Jaheruddin
  • 21,208
  • 8
  • 66
  • 122