Take String Before and After 'First' Space Character

Take string before and after 'First' space character

Your issue is because of how you are splitting your content. You have separated your content on a space, but then you have created an array with four different indexes. You can solve a couple of different approaches.

var sentence = "White wine extra offer";
var words = sentence.Split(' ');

var white = words.FirstOrDefault();
var wineExtraOffer = String.Join(" ", words.Skip(1));

You also should realize that if you manipulate a string directly with Linq, it will treat as a char[]. So you need to ensure you do not use the same variable for a bunch of Linq while assigning values.

Fiddle with output.

How to split a string at the first space

You can use strtok to split your string. Here is the man page.

In this specific case, it is enough to find the first space and split.

char *s1;
char *s2;
char *sp;

sp = strchr(line, ' ');
if (!sp) { exit(EXIT_FAILURE); }

s1 = strndup(line, sp-line); /* Copy chars until space */
s2 = sp+1; /* Skip the space */

...

free(s1);

PHP - Extract characters before and after first space

What have you tried?

suggestion: explode() your string on the space character, get the first and last values in the array by index, then use substr() to fetch the characters you require.

Get all the string elements after first space

We can use sub with pattern \\S+ (one or more non-white space) followed by one or more white space to remove the prefix or we can remove the white space followed by non white space to remove the suffix.

sub("^\\S+\\s+", '', vec1)
sub("\\s+\\S+$", '', vec1)

Or use read.table to convert this to a data.frame with two columns and then extract those columns

d1 <- read.table(text= vec1, header=FALSE, stringsAsFactors=FALSE)
v1 <- d1[,1]
v2 <- d1[,2]

Or another option is strsplit to split it to a list and then extract the list elements.

lst <- strsplit(vec1, "\\s+")
v1 <- sapply(lst ,`[`, 1)
v2 <- sapply(lst, `[`, 2)

data

vec1 <- c("rrrt rrr", "tttt   gg", "tt pp", "hhhh      k")

How to extract part of text that comes before first space in string?

The simplest method is:

select (case when PersonalInfoName like '% %'
then left(PersonalInfoName, charindex(' ', PersonalInfoName) - 1))
else PersonalInfoName
end)

There is probably no need to write your own function to do this.



Related Topics



Leave a reply



Submit