# How do i delete the spaces that are in the middle of a string array?

조회 수: 8(최근 30일)
Sameer Raza 2022년 7월 25일
답변: Githin George 2022년 7월 26일
str=' 123 456 ';
strtrim(str)
strfind('123 456',' ')
so far i know that using strtrim will remove the leading and trailing blanks in the string vector but how do i remove the space that is between 123 and 456? i can use strfind to help me know which element of the string vector is a blank space but how would i be able to delete the elements themselves?

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

### 답변(4개)

the cyclist 2022년 7월 25일
Here is one way:
str=' 123 456 ';
str(str==' ') = []
str = '123456'
This method relies on the fact that the white space is a space character (and not some of the other whitespace characters).
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Voss 2022년 7월 25일
To delete elements from an array, set them to [] (or '').
% to removes spaces (' '):
str=' 123 456 ';
str(str == ' ') = []
str = '123456'
% this also works:
str=' 123 456 ';
str(str == ' ') = ''
str = '123456'
% to remove any whitespace:
str=' 123 456 ';
str(isstrprop(str,'wspace')) = []
str = '123456'
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Paul 2022년 7월 26일
replace seems to do the trick
Single char:
str=' 123 456 ';
replace(str,whitespacePattern,'')
ans = '123456'
Cell array of chars
replace({str;str},whitespacePattern,'')
ans = 2×1 cell array
{'123456'} {'123456'}
String array
str1 = string(str)
str1 = " 123 456 "
replace([str1;str1],whitespacePattern,'')
ans = 2×1 string array
"123456" "123456"
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

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

Githin George 2022년 7월 26일
Hi Sameer,
My understanding is that you would like to remove any and all multiple spaces from your string to single space and trim the start and end. You could to use the following code to get it done.
mystr = ' Some string one ';
% \s+ means multiple spaces
mystr = regexprep(mystr,'\s+',' ');
strtrim(mystr)
ans = 'Some string one'
I hope it helps!

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

### 범주

Find more on Characters and Strings in Help Center and File Exchange

R2022a

### Community Treasure Hunt

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

Start Hunting!

Translated by