Hi,
I am trying to convert first letter of a word to upper case.With the below code it is working fine.I am able to convert to uppercase after finding the first period.If there is one more period in a sentence then the preceding char is still in lower case.
Ex:today it is too cold.its raining continuously.everyone should wear sweaters.
With the below code:
Today it is too cold.Its raining continuously.everyone should wear sweaters.
Below is the code:
size_t j=0;
for(size_t i=0;i<n.length();++i)
{
j=n.find('.'); //Finding the period from a string.
Hi xerzi,
Thanks for your response.I tried ur code.If i use while loop how will it terminate from the loop?Also i wanted to convert the first char of all the letters in the sentence.Let me know if my understanding is wrong.
There is meant to be a space after a period in your ex.
In that case, if you find the period, n[i+2] has to be converted to upper case.
There is no need for the if (islower) statements and the first capitalization (when i==0)is a one off and does not need to be coupled with an else statement.
Hi Buffbill,
Sorry.I didnot get u.Actually i wanted to convert first letter of all the words in a sentence.With the above code it is working fine.Problem is existing when there is a period between the sentences.After period i am not able to convert the first char to upper.
You are using this code to find a period. This will only find the first one in the sentence so you are only going to do it for the first period in a sentence.
j=n.find('.');
Instead of using the find() function why don't you just add an if statement for a '.' since you are already looping through the entire string.
size_t j=0; // should use std::string::size_type instead of size_t, altho size_t is the same type it here, that may not always be the case for other systems
for(size_t i=0;i<n.length();++i)
{
j=n.find('.'); // will only get position of first period always...
if(i==0)
{
if(islower(n[i])) // dont need these checks since the operation is rather simple you don't really save any time doing this
n[i]=toupper(n[i]);
}
elseif(n[i]!=' ')
{
if(isupper(n[i])) // here too
{
n[i]=tolower(n[i]);
}
}
else
{
i++;
if(islower(n[i])) // here too
n[i]=toupper(n[i]);
}
if(j)
{
if(islower(n[j+1])) // here too
n[j+1]=toupper(n[j+1]);
}
}