Heartsuit's Simple Blog

A place to hold mainly reading notes, and some technical stuff occasionally. 这里主要是一些读书笔记、感悟;还有部分技术相关的内容。


Project maintained by heartsuit Hosted on GitHub Pages — Theme by mattgraham

MATLAB中去掉字符串中的空格,num2str()引发的问题

目录[-]

去掉前后的空格:strtrim();

eg:

	>> a = ' Keep Moving ', aLen = length(a)
	a =
	 Keep Moving
	aLen =
	    13
	>> b = strtrim(a), bLen = length(b)
	b =
	Keep Moving
	bLen =
	    11

去掉字符串所有(包括前后以及内部)的空格

这个好像没有专门的函数,不过可以转化一下,通过替换实现:strrep();

eg:

	>> a = ' Keep Moving ', aLen = length(a)
	a =
	 Keep Moving
	aLen =
	    13
	>> c = strrep(a, ' ', ''), cLen = length(c)
	c =
	KeepMoving
	cLen =
	    10

引发上述问题的原因是我要用到num2str()函数将一个double型的行向量(仅包含0, 1)转化为一个二进制串,那么问题来了:

	>> m = [0, 1, 0, 1], mLen = length(m)
	m =
	     0     1     0     1
	mLen =
	     4
	>> n = num2str(m), nLen = length(n)
	n =
	0  1  0  1
	nLen =
	    10

由于后面要用到这个二进制串,刚开始程序一直报错,后来进行单步调试,发现这个串长度很怪异; 原来,在将向量转化为串时,MATLAB默认会在每个数后面加两个空格,所以需要想办法处理掉这些空格。


「说点什么吧😊~~😊」: