How do I add space between any specific word in string

6 ビュー (過去 30 日間)
Sagar Talaviya
Sagar Talaviya 2018 年 1 月 28 日
回答済み: Voss 2024 年 10 月 21 日
Here is string,
str = 'double function_name(double name1, float name2, double name3)'
I want that string with one white space after each word and symbol, like this;
newstr = 'double function_name ( double name1 , float name2 , double name3 )'

回答 (3 件)

BhaTTa
BhaTTa 2024 年 10 月 21 日
Hey @Sagar Talaviya, you can make use of regular expression to acheive the above requirement, I have attached the code please take it as reference and modify accordingly
% Original string
str = 'double function_name(double name1, float name2, double name3)';
% Use regexprep to insert a space after each word and symbol, but avoid adding before underscores
newstr = regexprep(str, '(\+|\(|\)|,)', '$1 ');
% Trim any trailing spaces
newstr = strtrim(newstr);
% Display the result
disp('Formatted String:');
Formatted String:
disp(newstr);
double function_name( double name1, float name2, double name3)
Hope it helps.

Image Analyst
Image Analyst 2024 年 10 月 21 日
% Original string
str = 'double function_name(double name1, float name2, double name3)';
% Use strrep to add spaces before and after parentheses and commas.
% Assumes there is no space already around the parentheses.
str = strrep(str, '(', ' ( ');
str = strrep(str, ')', ' ) ');
str = strrep(str, ',', ' ,'); % Add space before, but not after (assumes there is already a space after).
% Trim any trailing spaces
newstr = strtrim(str)
newstr = 'double function_name ( double name1 , float name2 , double name3 )'

Voss
Voss 2024 年 10 月 21 日
str = 'double function_name(double name1, float name2, double name3)'
str = 'double function_name(double name1, float name2, double name3)'
newstr = strtrim(strrep(regexprep(str,'([\(\),])',' $1 '),' ',' '))
newstr = 'double function_name ( double name1 , float name2 , double name3 )'

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by