replace spaces in a string
160 次查看(过去 30 天)
显示 更早的评论
Im doing a practice question and I got the question:
Replace any occurrence of two or more consecutive blank spaces with one (single) blank space
I attempted it a bunch of ways but so far the code Ive got is:
str = input('Enter a string: ');
[m, n] = size(str);
C = 0;
for i=1:n
if str(i) == ' '
C = C+1;
blankpos(C) = i;
end
end
fprintf('Position of the blank spaces: \n');
blankpos
C1 = 0;
strm=str;
for i=1:n
if str == ' '
C1 = C1+1;
posreplace(C1)=i;
if str == ' '
C1 = C1+1;
posreplace(C1)=i;
end
end
end
strm(posreplace) = ' ';
fprintf('The modified string: ');
strm
0 个评论
采纳的回答
更多回答(2 个)
Image Analyst
2018-1-8
One way is to use strrep():
s = 'a a a a' % Test string.
% Repeatedly loop replacing double spaces by single space
% until there are no double spaces left.
while contains(s, ' ')
s = strrep(s, ' ', ' ');
end
s % Display in command window.
2 个评论
Image Analyst
2018-1-8
Did you try it? It works with any number of spaces.
However, Walter's answer looks like the best answer to me.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!