我试图从字符串中读取未知数量的数值。
例如:
line = 'bla bal bli : 3 5 12 15 266'
我试过sscanf
,但它需要我知道字符串中有多少数字。
答案 0 :(得分:6)
您只需使用isstrprop
。
line = 'bla bal bli : 3 5 12 15 266'
line(isstrprop(line, 'digit'))
您从字符串中提取数字:
line =
bla bal bli : 3 5 12 15 266
ans =
351215266
答案 1 :(得分:3)
如果要从字符串中提取整数,可以使用正则表达式:
将数字作为字符串的单元格数组:
>> line = 'bla bal bli : 3 5 12 15 266';
>> regexp(line,'(?<!\d)(\d)+(?!\d)','match')
ans =
'3' '5' '12' '15' '266'
要将数字作为数字向量:
>> str2double(regexp(line,'(?<!\d)(\d)+(?!\d)','match'))
ans =
3 5 12 15 266
答案 2 :(得分:1)
如果你的字符串在字母和数字之间总是有一个像冒号(':'
)这样的分隔符,你可以使用strsplit
只用数字来提取字符串的一部分,这将是比使用正则表达式更快:
line = 'bla bal bli : 3 5 12 15 266';
numstr = strsplit(line,':');
然后您可以使用sscanf
将数字提取为双精度数组:
nums = sscanf(numstr{2},'%u') % Assuming digits are always unsigned, if not use %d
如果您使用的是R2012b或更早版本,则不会有strsplit
。有关替代方案,请参阅this answer。
答案 3 :(得分:0)
如果有可能是负数或十进制数,正则表达式可以这样更新:
1 function Dijkstra(Graph, source):
2
3 create vertex set Q
4
5 for each vertex v in Graph: // Initialization
6 dist[v] ← INFINITY // Unknown distance from source to v
7 prev[v] ← UNDEFINED // Previous node in optimal path from source
8 add v to Q // All nodes initially in Q (unvisited nodes)
9
10 dist[source] ← 0 // Distance from source to source
11
12 while Q is not empty:
13 u ← vertex in Q with min dist[u] // Node with the least distance will be selected first
14 remove u from Q
15
16 for each neighbor v of u: // where v is still in Q.
17 alt ← dist[u] + length(u, v)
18 if alt < dist[v]: // A shorter path to v has been found
19 dist[v] ← alt
20 prev[v] ← u
21
22 return dist[], prev[]
示例:
str2double(regexp(line,'(-?\d+\.?\d?)','match'))
ans =
3 5 12 15 266
str2double(regexp('bla bal bli : 3 5 12 15 266','(-?\d+\.?\d?)','match'))
ans =
3.0000 5.0000 12.0000 15.4000 -266.0000
答案 4 :(得分:0)
从16b开始,您可以使用字符串类
line = "bla bal bli : 3 5 12 15 266";
numbers = extractAfter(line,': ');
numbers = split(numbers);
numbers = double(numbers);
这似乎是最快的选择。
>> profFunc
Elapsed time is 0.088259 seconds.
Elapsed time is 1.558718 seconds.
Elapsed time is 1.482743 seconds.
function profFunc
n = 1E4;
tic;
for i = 1:n
line = "bla bal bli : 3 5 12 15 266";
numbers = extractAfter(line,': ');
numbers = split(numbers);
numbers = double(numbers);
end
toc
tic;
for i = 1:n
line = 'bla bal bli : 3 5 12 15 266';
numbers = str2double(regexp(line,'(?<!\d)(\d)+(?!\d)','match'));
end
toc
tic;
for i = 1:n
line = 'bla bal bli : 3 5 12 15 266';
numstr = strsplit(line,':');
nums = sscanf(numstr{2},'%u');
end
toc
end