How to recognise a specific format with textscan?

3 次查看(过去 30 天)
Hi!
I have a text file of some lines with this format:
1-Capital of France-5-Paris-0
2-............-6-soccer
etc
I want to use textscan and take only up to the number of letters the solution has, and then do the same with only the solution. It must work for any field with the format above:
I have tried different things, but I really don't know how to do it.
Thank you.
  1 个评论
dpb
dpb 2013-12-7
What does "...take only up to the number of letters the solution has" mean, precisely. What is a solution in this context?
Also, the sample you posted is shown as a single line...where's the line break actually located? Unfortunately, TMW can't seem to get into their heads that a coding forum shouldn't have linewrap on as a default so you'll have to format the file as code to get it to show up properly. Put a couple of blanks in front of the first line w/ a line break in front of it and then break the lines where supposed to be. Observe in Preview window and keep working until it looks right there.
Just as a guess, it looks like you using
'delimiter','-'
might solve most of your problems altho variable-length character fields can be a pit(proverbial)a...

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2013-12-7
If you want to use textscan to read this, then you will need to request that it read only one item (a size), and then you will need to request that it read the dash followed by the appropriate size, such as in
nchar_c = textscan(fid, '%f-', 1);
str1 = textscan(fid, sprintf('%%%ds', nchar_c{1}), 1);
and keep going like that.
This would be a very inefficient use of textscan(), and it would be much more efficient to use fread() when you know how many characters you are going to read in.

类别

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