How to Change the first letter of a string to capital case and the rest to lowercase

조회 수: 111 (최근 30일)
impropermsg = input('Enter the sentence : \n', 's');
function propermsg = changemsg(impropermsg)
propermsg = strcat(upper(impropermsg(1)),lower(impropermsg(2:end)));
end
% The user can input but nothing happens
  댓글 수: 3
Les Beckham
Les Beckham 2020년 12월 13일
You created a function that looks like it will do what you want but (at least in the code you posted) you never called the function.
You could just eliminate the 2nd and 4th lines of this code and you will have a simple two line script that does what you want (with the answer being in the propermsg string). If you want the result to be displayed, just take the semicolon off of the end of the propermsg = ... line.
sydney salvador
sydney salvador 2020년 12월 16일
Thank you for the feedback, I will remember the structure next time

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

채택된 답변

Image Analyst
Image Analyst 2020년 12월 13일
Make a script called something like test.m, and put this into it:
impropermsg = input('Enter the sentence : \n', 's');
% Now call the function:
propermsg = changemsg(impropermsg);
fprintf('The result is "%s"\n', propermsg);
function propermsg = changemsg(impropermsg)
propermsg = strcat(upper(impropermsg(1)),lower(impropermsg(2:end)));
end

추가 답변 (2개)

mahmoud abdelaal
mahmoud abdelaal 2022년 10월 3일
이동: Image Analyst 2022년 10월 3일
word='si'
word = 'si'
new=replace(word,word(1),upper(word(1)))
new = 'Si'
  댓글 수: 1
Image Analyst
Image Analyst 2022년 10월 3일
That doesn't replace the rest with lower case like requested:
word='siUPPERCASE'
word = 'siUPPERCASE'
new=replace(word,word(1),upper(word(1)))
new = 'SiUPPERCASE'
You'd need to add this line:
new = replace(new, word(2:end), lower(word(2:end)))
new = 'Siuppercase'

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


Toshiaki Takeuchi
Toshiaki Takeuchi 2024년 6월 4일
편집: Walter Roberson 2024년 6월 5일
str = "test";
pat = lineBoundary("start")+lettersPattern(1);
new_str = replace(str,pat,(upper(extract(str,pat))))
new_str = "Test"

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by