필터 지우기
필터 지우기

replace spaces in a string

조회 수: 188 (최근 30일)
Mitul Dattani
Mitul Dattani 2018년 1월 8일
댓글: nagendra badiger 2020년 7월 22일
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

채택된 답변

Walter Roberson
Walter Roberson 2018년 1월 8일
str = regexprep(str, ' +', ' ');
  댓글 수: 1
nagendra badiger
nagendra badiger 2020년 7월 22일
Really elegant solution

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Image Analyst
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
Mitul Dattani
Mitul Dattani 2018년 1월 8일
what if there are triple spaces thats hats tripping me up as in the question im given theres a triple space
Image Analyst
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.

댓글을 달려면 로그인하십시오.


Jan
Jan 2018년 1월 8일
편집: Jan 2018년 1월 8일
s = 'a a a a b bcd a ';
[B, N] = RunLength(s);
N(B == ' ') = 1;
s = RunLength(B, N);

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by