Extract the first 2 Characters in a string
You can just use the substr
function directly to take the first two characters of each string:
x <- c("75 to 79", "80 to 84", "85 to 89")
substr(x, start = 1, stop = 2)
# [1] "75" "80" "85"
You could also write a simple function to do a "reverse" substring, giving the 'start' and 'stop' values assuming the index begins at the end of the string:
revSubstr <- function(x, start, stop) {
x <- strsplit(x, "")
sapply(x,
function(x) paste(rev(rev(x)[start:stop]), collapse = ""),
USE.NAMES = FALSE)
}
revSubstr(x, start = 1, stop = 2)
# [1] "79" "84" "89"
How to get the first 2 letters of a string in Python?
It is as simple as string[:2]
. A function can be easily written to do it, if you need.
Even this, is as simple as
def first2(s):
return s[:2]
Extract first two characters of a String in Java
Your code looks great! If you wanted to make it shorter you could use the ternary operator:
public String firstTwo(String str) {
return str.length() < 2 ? str : str.substring(0, 2);
}
How to extract the first X characters of a string and use them into another in C
You are missing the string's NUL terminator '\0' so it keeps printing until it finds one.
Declare it like:
char pre_salt[3]={0,0,0};
And problem solved.
Extract the first (or last) n characters of a string
See ?substr
R> substr(a, 1, 4)
[1] "left"
extract the first two characters from a list of names in r
We can use str_extract_all
to extract two characters after the word boundary
library(stringr)
library(dplyr)
library(purrr)
df1 %>%
mutate(two_chars = str_extract_all(list_names, "\\b[a-z]{2}") %>%
map_chr(toString))
# id list_names two_chars
#1 1 john jo
#2 2 adam, sally ad, sa
#3 3 rebecca re
#4 4 zhang, mike, antonio zh, mi, an
#5 5 mark, henry, scott, john, steve, jason, nancy ma, he, sc, jo, st, ja, na
Or using gsub
gsub("\\b([a-z]{2})[^,]+", "\\1", df1$list_names)
#[1] "jo" "ad, sa" "re" "zh, mi, an"
#[5] "ma, he, sc, jo, st, ja, na"
Get First 2 Characters In a String
Second arg should be $s
, see printf()
printf("[%0.2s]\n", $s);
Related Topics
What Are Replacement Functions in R
Converting Multiple Columns from Character to Numeric Format in R
Error - Replacement Has [X] Rows, Data Has [Y]
Replace Na in Column With Value in Adjacent Column
Horizontal/Vertical Line in Plotly
Add Correct Century to Dates With Year Provided as "Year Without Century", %Y
How to Convert Long to Wide Format With Counts
Yaml Current Date in Rmarkdown
Basic Lag in R Vector/Dataframe
Create a Group Number For Each Consecutive Sequence
Concatenate Strings by Group With Dplyr
How to Match Fuzzy Match Strings from Two Datasets