I have a string and I want to split the string after every 2nd comma. Is this doable using split string in c#?
Example string:
"This,is,an, example,for,the,stackoverflow,community"
Desired output
This,is
an,example
for,the
stackoverflow,community
Any help would be much appreciated thanks!
Using Enumerable.Chunk from .NET 6, you can
split on ",",
create chunks of two items each and
re-join those chunks:
string input = "This,is,an,example,for,the,stackoverflow,community";
var output = input.Split(",")
.Chunk(2)
.Select(chunk => string.Join(",", chunk));
foreach (string s in output)
Console.WriteLine(s);
fiddle
If you're stuck with the "classic" .NET Framework, here are chunk implementations for .NET < 6:
how do I chunk an enumerable?
You could do something like this:
var s = "This,is,an, example,for, the, stackoverflow, community";
var a = ("," + s + ",").Split(',');
// requires using System.Linq;
var b = Enumerable.Range(0, a.Length / 2)
.Select(i => $"{a[2 * i]}, {a[2 * i + 1]}".Trim(',', ' '));
Range enumerates the resulting array and computes concatenations of the corresponding pairs of strings.
You could also use a pattern to match 1 or more characters except for a comma using a negated character class [^,]+ before and after the comma:
string pattern = #"[^,]+,[^,]+";
string input = "This,is,an, example,for,the,stackoverflow,community";
foreach (Match m in Regex.Matches(input, pattern))
{
Console.WriteLine(m.Value);
}
Output
This,is
an, example
for,the
stackoverflow,community
Related
I'm trying to create a program that splits a string to an array then adds
to that array.
Splitting the string works but adding to the array is really putting up a
fight.
//here i create the text
string text = Console.ReadLine();
Console.WriteLine();
//Here i split my text to elements in an Array
var punctuation = text.Where(Char.IsPunctuation).Distinct().ToArray();
var words = text.Split().Select(x => x.Trim(punctuation));
//here i display the splitted string
foreach (string x in words)
{
Console.WriteLine(x);
}
//Here a try to add something to the Array
Array.words(ref words, words.Length + 1);
words[words.Length - 1] = "addThis";
//I try to display the updated array
foreach (var x in words)
{
Console.WriteLine(x);
}
//Here are the error messages |*error*|
Array.|*words*|(ref words, words.|*Length*| + 1);
words[words.|*Length*| - 1] = "addThis";
'Array' does not contain definition for 'words'
Does not contain definition for Length
Does not contain definition for length */
Convert the IEnumerable to List:
var words = text.Split().Select(x => x.Trim(punctuation)).ToList();
Once it is a list, you can call Add
words.Add("addThis");
Technically, if you want to split on punctuation, I suggest Regex.Split instead of string.Split
using System.Text.RegularExpressions;
...
string text =
#"Text with punctuation: comma, full stop. Apostroph's and ""quotation?"" - ! Yes!";
var result = Regex.Split(text, #"\p{P}");
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
Text with punctuation # Space is not a punctuation, 3 words combined
comma
full stop
Apostroph # apostroph ' is a punctuation, split as required
s and
quotation
Yes
if you want to add up some items, I suggest Linq Concat() and .ToArray():
string text =
string[] words = Regex
.Split(text, #"\p{P}")
.Concat(new string[] {"addThis"})
.ToArray();
However, it seems that you want to extract words, not to split on puctuation which you can do matching these words:
using System.Linq;
using System.Text.RegularExpressions;
...
string text =
#"Text with punctuation: comma, full stop. Apostroph's and ""quotation?"" - ! Yes!";
string[] words = Regex
.Matches(text, #"[\p{L}']+") // Let word be one or more letters or apostrophs
.Cast<Match>()
.Select(match => match.Value)
.Concat(new string[] { "addThis"})
.ToArray();
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
Text
with
punctuation
comma
full
stop
Apostroph's
and
quotation
Yes
addThis
I have the following string:
string x = "hello;there;;you;;;!;"
The result I want is a list of length four with the following substrings:
"hello"
"there;"
"you;;"
"!"
In other words, how do I split on the last occurrence when the delimiter is repeating multiple times? Thanks.
You need to use a regex based split:
var s = "hello;there;;you;;;!;";
var res = Regex.Split(s, #";(?!;)").Where(m => !string.IsNullOrEmpty(m));
Console.WriteLine(string.Join(", ", res));
// => hello, there;, you;;, !
See the C# demo
The ;(?!;) regex matches any ; that is not followed with ;.
To also avoid matching a ; at the end of the string (and thus keep it attached to the last item in the resulting list) use ;(?!;|$) where $ matches the end of string (can be replaced with \z if the very end of the string should be checked for).
It seems that you don't want to remove empty entries but keep the separators.
You can use this code:
string s = "hello;there;;you;;;!;";
MatchCollection matches = Regex.Matches(s, #"(.+?);(?!;)");
foreach(Match match in matches)
{
Console.WriteLine(match.Captures[0].Value);
}
string x = "hello;there;;you;;;!;"
var splitted = x.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptryEntries);
foreach (var s in splitted)
Console.WriteLine("{0}", s);
I am new to c#, i need to trim a sentence which has many words. I need only first characters in all the words. For example
If a sentence is like this.
input : Bharat Electrical Limited => output : BEL
how do i accomplish this in c#?
Thanks in advance
Try
string sentence = "Bharat Electrical Limited";
var result = sentence.Split(' ').Aggregate("", (current, word) => current + word.Substring(0, 1));
EDIT: Here's a brief explanantion:
sentence.Split(' ') splits the string into elements based on space (' ')
.Aggregate("", (current, word) => current + word.Substring(0, 1)); is a linq expression to iterate through every word retrieve above perform an operation on it and
word.Substring(0, 1) returns the first letter of every word
This is the sort of thing that's easily accomplished with a regular expression:
s = Regex.Replace(s, #"(\S)\S*\s*", "$1");
This effectively matches consecutive non-white space characters, followed by white space, and replaces the whole sequence by its first character.
You can do something like this -
string sentence = "Bharat Electrical Limited";
//Split the words
var letters = sentence.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
//Take firsst letter of every word
var myAbbWord = letters.Aggregate(string.Empty, (current, letter) => current + letter.First());
myAbbWord should display BEL for you.
Here is the solution.
I hope it helps.
string str1 = "Bharat Electrical Limited";
var resultList = str1.Split(' ');
string result = resultList.Aggregate(String.Empty, (current, word) => current + word.First());
First thing you want to Split the string into words, then take First letter from each word. You can do this by a simple for loop like the following:
string inputStr = "Bharat Electrical Limited";
List<char> firstChars = new List<char>();
foreach (string word in inputStr.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries))
{
firstChars.Add(word[0]); // Collecting first chars of each word
}
string outputStr = String.Join("", firstChars);
And this will be the Short way for this:
string inputStr = "Bharat Electrical Limited";
string shortWord = String.Join("", inputStr.Split(new char[]{' '},StringSplitOptions.RemoveEmptyEntries).Select(x => x[0]));
If the first character in each string is not Caps, then you can use any of the following options.
Make the input into Title cased sentence, before performing the action.
For this you can use the following code:
inputStr = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(inputStr.ToLower());
Convert the Character to uppercase while we collect Characters from the word,
This can be achieved by:
firstChars.Add(char.ToUpper(word[0])); // For the first case
.Select(x => char.ToUpper(x[0])) // For the second case
Here you can find a working example for all above mentioned cases
Simplest way is :
string inputStr = "Bharat Electrical Limited";
string result = new String(inputStr.Split(' ').Select(word => (word[0])).ToArray());
// BEL
You need to add using System.Linq; to your source file.
Logic is:
Split the string into array or words (delimited by space), then project this array by selecting the first char of each string. The result is an array of the first characters. Then using the String overload constructor taking char array, construct the result string.
This might looks more friendly to you
string intput = "Bharat Electrical Limited";
string output = string.Join( "",intput.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries)
.Select(a => a.First()));
First split your input sentense with space and then use First() extension on string to get first character of string
Use this method
string inputStr = "Bharat Electrical Limited";
var arrayString = string.Join("", inputStr.Split(' ').Select(x => x[0]));
I need an solution for my problem. I have a clause like:
Hello guys I am cool (test)
An now I need an effective method to split just only the part in the parentheses and the result should be:
test
My try is to split the String in words like. But I don't think it is the best way.
string[] words = s.Split(' ');
I do not think that split is the solution to your problem
Regex is very good for extracting data.
using System.Text.RegularExpression;
...
string result = Regex.Match(s, #"\((.*?)\)").Groups[1].Value;
This should do the trick.
Assuming:
var input = "Hello guys I am cool (test)";
..Non-Regex version:
var nonRegex = input.Substring(input.IndexOf('(') + 1, input.LastIndexOf(')') - (input.IndexOf('(') + 1));
..Regex version:
var regex = Regex.Match(input, #"\((\w+)\)").Groups[1].Value;
You can use regex for this:
string parenthesized = Regex.Match(s, #"(?<=\()[^)]+(?=\))").Value;
Here's an explanation of the various parts of the regex pattern:
(?<=\(): Lookbehind for the ( (excluded from the match)
[^)]+: Sequence of characters consisting of anything except )
(?=\)): Lookahead for the ) (excluded from the match)
The most efficient way is using string methods but you don't need Split but Substring and IndexOf. Note that this currently just finds a single word in parentheses:
string text = "Hello guys I am cool (test)";
string result = "--no parentheses--";
int index = text.IndexOf('(');
if(index++ >= 0) // ++ used to look behind ( which is a single character
{
int endIndex = text.IndexOf(')', index);
if(endIndex >= 0)
{
result = text.Substring(index, endIndex - index);
}
}
string s = "Hello guys I am cool (test)";
var result = s.Substring(s.IndexOf("test"), 4);
I have a string of the form:
codename123
Is there a regular expression that can be used with Regex.Split() to split the alphabetic part and the numeric part into a two-element string array?
I know you asked for the Split method, but as an alternative you could use named capturing groups:
var numAlpha = new Regex("(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)");
var match = numAlpha.Match("codename123");
var alpha = match.Groups["Alpha"].Value;
var num = match.Groups["Numeric"].Value;
splitArray = Regex.Split("codename123", #"(?<=\p{L})(?=\p{N})");
will split between a Unicode letter and a Unicode digit.
Regex is a little heavy handed for this, if your string is always of that form. You could use
"codename123".IndexOfAny(new char[] {'1','2','3','4','5','6','7','8','9','0'})
and two calls to Substring.
A little verbose, but
Regex.Split( "codename123", #"(?<=[a-zA-Z])(?=\d)" );
Can you be more specific about your requirements? Maybe a few other input examples.
IMO, it would be a lot easier to find matches, like:
Regex.Matches("codename123", #"[a-zA-Z]+|\d+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();
rather than to use Regex.Split.
Well, is a one-line only: Regex.Split("codename123", "^([a-z]+)");
Another simpler way is
string originalstring = "codename123";
string alphabets = string.empty;
string numbers = string.empty;
foreach (char item in mainstring)
{
if (Char.IsLetter(item))
alphabets += item;
if (Char.IsNumber(item))
numbers += item;
}
this code is written in java/logic should be same elsewhere
public String splitStringAndNumber(String string) {
String pattern = "(?<Alpha>[a-zA-Z]*)(?<Numeric>[0-9]*)";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(string);
if (m.find()) {
return (m.group(1) + " " + m.group(2));
}
return "";
}