How to Capitalize First Letter of First Word in a Sentence

Capitalize the first word of a sentence in a text

When you split the string by ". " that removes the ". "s from your string and puts the rest of it into a list. You need to add the lost periods to your sentences to make this work.

Also, this can result in the last sentence to have double periods, since it only has "." at the end of it, not ". ". We need to remove the period (if it exists) at the beginning to make sure we don't get double periods.

text = input("Enter the text: \n")
output = ""
if (text[-1] == '.'):
# remove the last period to avoid double periods in the last sentence
text = text[:-1]
lines = text.split('. ') #Split the sentences

for line in lines:
a = line[0].capitalize() # capitalize the first word of sentence
for i in range(1, len(line)):
a = a + line[i]
a = a + '.' # add the removed period
output = output + a
print (output)

We can also make this solution cleaner:

text = input("Enter the text: \n")
output = ""

if (text[-1] == '.'):
# remove the last period to avoid double periods in the last sentence
text = text[:-1]
lines = text.split('. ') #Split the sentences

for line in lines:
a = line[0].capitalize() + line [1:] + '.'
output = output + a
print (output)

By using str[1:] you can get a copy of your string with the first character removed. And using str[:-1] will give you a copy of your string with the last character removed.

How to capitalize first letter of first word in a sentence?

$output = preg_replace('/([.!?])\s*(\w)/e', "strtoupper('\\1 \\2')", ucfirst(strtolower($input)));

Since the modifier e is deprecated in PHP 5.5.0:

$output = preg_replace_callback('/([.!?])\s*(\w)/', function ($matches) {
return strtoupper($matches[1] . ' ' . $matches[2]);
}, ucfirst(strtolower($input)));

Capitalizing the first letter of the first word in a sentence using StringBuilder

The error has occurred because you are trying to access the characters of Sentence StringBuilder which is empty as you haven't appended any string in the beginning. Hence we need to initialize the StringBuilder with a random Article first and then perform the capitalization as follows:

StringBuilder buffer = new StringBuilder();
StringBuilder Sentence = new StringBuilder(Article[index[0]]);
//capitalization attempt
Sentence = buffer.append(Sentence.substring(0,1).toUpperCase() + Sentence.substring(1)).append(" ").append(Noun[index[1]]).append(" ").append(Verb[index[2]]).append(" ").append(Preposition[index[3]]).append(" ").append(Article[index[4]]).append(" ").append(Noun[index[5]]).append(".");

Please note that I have removed the .append(Article[index[0]]) part as we already have done that in the StringBuilder initialization.

Prints:

The dog walked under   one boy.
The girl drove over some car.
A town jumped from a town.
Some boy walked to a dog.
A dog jumped to some girl.
...and so on...

RandomSentence Method:

    public static StringBuilder RandomSentence()
{
Random rand = new Random();
int[] index = new int[6];


for (int i = 0; i<6; i++){
index[i] = rand.nextInt(5);
}
StringBuilder buffer = new StringBuilder();
StringBuilder Sentence = new StringBuilder(Article[index[0]]);
//capitalization attempt
Sentence = buffer.append(Sentence.substring(0,1).toUpperCase() + Sentence.substring(1)).append(" ").append(Noun[index[1]]).append(" ").append(Verb[index[2]]).append(" ").append(Preposition[index[3]]).append(" ").append(Article[index[4]]).append(" ").append(Noun[index[5]]).append(".");
return Sentence;
}

PHP: How to capitalize first letter of first word in a sentence, including a set of non-ASCII values?

Apply a limit so that only 1 character is replaced:

$output = preg_replace('/[a-z]/e', 'strtoupper("$0")', strtolower($input), 1);

Though you should be using preg_replace_callback() rather than the /e switch nowadays:

$output = preg_replace_callback(
'/[a-z]/',
function($matches) { return strtoupper($matches[0]); },
strtolower($string),
1
);

EDIT

After the scope creep of changing the question to require UTF8 handling:

$output = preg_replace_callback(
'/\p{L}/u',
function($matches) { return mb_strtoupper($matches[0]); },
mb_strtolower($string),
1
);

How to capitalize the first character of each word, or the first character of a whole string, with C#?

As discussed in the comments of @miguel's answer, you can use TextInfo.ToTitleCase which has been available since .NET 1.1. Here is some code corresponding to your example:

string lipsum1 = "Lorem lipsum et";

// Creates a TextInfo based on the "en-US" culture.
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo;

// Changes a string to titlecase.
Console.WriteLine("\"{0}\" to titlecase: {1}",
lipsum1,
textInfo.ToTitleCase( lipsum1 ));

// Will output: "Lorem lipsum et" to titlecase: Lorem Lipsum Et

It will ignore casing things that are all caps such as "LOREM LIPSUM ET" because it is taking care of cases if acronyms are in text so that "IEEE" (Institute of Electrical and Electronics Engineers) won't become "ieee" or "Ieee".

However if you only want to capitalize the first character you can do the solution that is over here… or you could just split the string and capitalize the first one in the list:

string lipsum2 = "Lorem Lipsum Et";

string lipsum2lower = textInfo.ToLower(lipsum2);

string[] lipsum2split = lipsum2lower.Split(' ');

bool first = true;

foreach (string s in lipsum2split)
{
if (first)
{
Console.Write("{0} ", textInfo.ToTitleCase(s));
first = false;
}
else
{
Console.Write("{0} ", s);
}
}

// Will output: Lorem lipsum et

How can I capitalize the first letter of each word in a string?

The .title() method of a string (either ASCII or Unicode is fine) does this:

>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'

However, look out for strings with embedded apostrophes, as noted in the docs.

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

How can I capitalize the first letter of each word in a string using JavaScript?

You are not assigning your changes to the array again, so all your efforts are in vain. Try this:

function titleCase(str) {

var splitStr = str.toLowerCase().split(' ');

for (var i = 0; i < splitStr.length; i++) {

// You do not need to check if i is larger than splitStr length, as your for does that for you

// Assign it back to the array

splitStr[i] = splitStr[i].charAt(0).toUpperCase() + splitStr[i].substring(1);

}

// Directly return the joined string

return splitStr.join(' ');

}

document.write(titleCase("I'm a little tea pot"));

How to capitalize the first letter of word in a string using Java?

If you only want to capitalize the first letter of a string named input and leave the rest alone:

String output = input.substring(0, 1).toUpperCase() + input.substring(1);

Now output will have what you want. Check that your input is at least one character long before using this, otherwise you'll get an exception.



Related Topics



Leave a reply



Submit