Capitalize the first letter of both words in a two word string
The base R function to perform capitalization is toupper(x)
. From the help file for ?toupper
there is this function that does what you need:
simpleCap <- function(x) {
s <- strsplit(x, " ")[[1]]
paste(toupper(substring(s, 1,1)), substring(s, 2),
sep="", collapse=" ")
}
name <- c("zip code", "state", "final count")
sapply(name, simpleCap)
zip code state final count
"Zip Code" "State" "Final Count"
Edit This works for any string, regardless of word count:
simpleCap("I like pizza a lot")
[1] "I Like Pizza A Lot"
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"));
Capitalize the first letter of each word in a string except `in`, `the` `of`
You can apply a blacklisting approach with a PCRE RegEx:
(?<!^)\b(?:the|an?|[io]n|at|with|from)\b(*SKIP)(*FAIL)|\b(\pL)
This is a demo of what this regex matches.
In R:
x <- c('I like the pizza', 'The water in the pool', 'the water in the pool')
gsub("(?<!^)\\b(?:the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of)\\b(*SKIP)(*FAIL)|\\b(\\pL)", "\\U\\1", x, perl=T)
## => [1] "I Like the Pizza" "The Water in the Pool" "The Water in the Pool"
See IDEONE demo
Here is an article Words Which Should Not Be Capitalized in a Title with some hints on what words to include into the first alternative group.
The RegEx explanation:
(?<!^)
- only match the following alternatives if not at the start of a string (I added this restriction as in comments, there is a requirment that the first letter should always be capitalized.)\b
- a leading word boundary(?:the|an?|[io]n|at|with(?:out)?|from|for|and|but|n?or|yet|[st]o|around|by|after|along|from|of)
- the whitelist of the function words (CAN AND SHOULD BE EXTENDED!)\b
- trailing word boundary(*SKIP)(*FAIL)
- fail the match once the function word is matched|
- or...\b(\pL)
- Capture group 1 matching a letter that is a starting letter in the word.
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.
Program that takes a string with multiple words and capitalizes the first letter of each word (Python 3.x)
You need to skip the next 2 characters once you hit a space and handle the word-break. This is simpler with a while-loop.
while i < len(string):
if i == 0:
string2 += string[0].upper()
i += 1
continue
elif string[i] == ' ':
string2 += string[i]
string2 += string[i+1].upper()
i += 2
continue
elif string[i] != ' ':
string2 += string[i]
i += 1
print(string2)
However there is a much shorter, much more pythonic way to achieve the same result:
string = 'hey my'
retval = ' '.join(x.title() for x in string.split())
print(retval)
How to capitalize first character of each word in a string?
To capitalize all the words in a sentence, you can use re.sub
and re.findall
:
import re
def capitalize_string(s):
return re.sub('(?<=^)[a-z]|(?<=\s)[a-z]', '{}', s).format(*map(str.upper, re.findall('(?<=^)[a-z]|(?<=\s)[a-z]', s)))
strings = ['q w e r G H J K M', 'hello world lol', "1 w 2 r 3g"]
result = list(map(capitalize_string, strings))
Output:
['Q W E R G H J K M', 'Hello World Lol', '1 W 2 R 3g']
Related Topics
Subset Dataframe by Multiple Logical Conditions of Rows to Remove
Select Groups Which Have At Least One of a Certain Value
Conditional Merge/Replacement in R
Subset Data Frame Based on Multiple Conditions
Change Bar Plot Colour in Geom_Bar With Ggplot2 in R
Efficiently Generate a Random Sample of Times and Dates Between Two Dates
Change Timezone in a Posixct Object
Creating a Comma Separated Vector
How to Extract a Single Column from a Data.Frame as a Data.Frame
How to Use Facets With a Dual Y-Axis Ggplot
Filtering a Data Frame on a Vector
Idiomatic R Code For Partitioning a Vector by an Index and Performing an Operation on That Partition
Test If Characters Are in a String
Convert Unix Epoch to Date Object