How can i remove a previous character present before the underscore including the underscore also.

3 次查看(过去 30 天)
I need to make my_john_sam as mjohsam. I need to remove underscore along with the character present just before underscore.
thanks

回答(2 个)

per isakson
per isakson 2015-10-1
编辑:per isakson 2015-10-1
Replace any one character followed by one underscore with empty string
>> regexprep( 'my_john_sam', '._', '' )
ans =
mjohsam
  2 个评论
Sam Johnson
Sam Johnson 2015-10-1
编辑:Walter Roberson 2015-10-1
Thank you...
i was doing like this
c='my_john_sam';
for i=1:length(c)
if (strfind(c,'_'))
x=strfind(c,'_');
for j=1:x
z=c(x-1:x);
d=strrep(c,z,'');
end
end
end
but i was remove only the 1st instance of underscore but not the second one.
per isakson
per isakson 2015-10-1
编辑:per isakson 2015-10-1
See Debug a MATLAB Program and try this
>> cssm('my_john_sam')
ans =
mjohsam
>> cssm('a string without underscore')
ans =
a string without underscore
where
function str = cssm( str )
ixs = strfind(str,'_');
for jj = fliplr( ixs )
z = str(jj-1:jj);
str = strrep(str,z,'');
end
end

请先登录,再进行评论。


Walter Roberson
Walter Roberson 2015-10-1
c='my_john_sam';
idx = c == '_';
c( idx|[idx(2:end), false]) = [];
or
c='my_john_sam';
idx = find(c == '_');
c([idx, idx-1]) = [];

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by