I have string:
string string1 = "0,11,22,33,5500,2000,9800,10,10,10,10,10,10,10,10,10,10,";
Now I have to split this string from 4th position of comma. I need to get values 5500,2000,9800 separately.
How can I split my string like this?
You can use LINQ and Skip:
var array = string1.Split(',').Skip(4).ToArray();
If you want to limit the elements of array (just want to get the 3 values):
var array = string1.Split(',').Skip(4).Take(3).ToArray();
I assume you don't know LINQ, so rember to import namespaces in order to use LINQ extension methods (if not imported):
using System.Linq;
EDIT (see comments):
var splitted = string1.Split(',');
var firstArr = splitted.Take(4);
var secondArray = splitted.Skip(4).Take(3);
var thirdArray = splitted.Skip(7);
If you want to have them like a string:
var s1 = string.Join(",", firstArray);
var s2 = string.Join(",", secondArray);
var s3 = string.Join(",", thirdArray);
.Why don't you do it like this:
string string1 = "0,11,22,33,5500,2000,9800,10,10,10,10,10,10,10,10,10,10,";
string[] parts = string1.Split(',');
As the OP asked a follow up question here is his answer:
To join the parts do it like this:
string firstPart = string.Join(",",parts.Take(4));
string secondPart = string.Join(",",parts.Skip(4).Take(3));
string thirdPart= string.Join(",",parts.Skip(7));
Related
I want to breakdown the string as searchText. The code is shown below:
"asarrivalFDate=06/12/2017arrivalTDate=20/12/2017" as
agentName= "as"
arrivalFDate= "06/12/2017"
arrivalTDate="20/12/2017".
How can I achieve in C#. Here "as" can be any input entered by user.
I want to break and pass individual to Linq.
This code could help you:
string input = "asarrivalFDate=06/12/2017arrivalTDate=20/12/2017";
string wordToRemove1 = "arrivalFDate";
string wordToRemove2 = "arrivalTDate";
input = input.Remove(input.IndexOf(wordToRemove1), wordToRemove1.Length);
input = input.Remove(input.IndexOf(wordToRemove2), wordToRemove2.Length);
string[] inputSplitted = input.Split('=');
string agentName = inputSplitted[0];
string arrivalFDate = inputSplitted[1];
string arrivalTDate = inputSplitted[2];
I am removing the arrivalFDate and the arrivalTDate from your string, and then I split the remaining part of your string with input.Split('='). Now you get a string array string[] inputSplitted that holds your desired values (agentName,arrivalFDate,arrivalTDate) from the input string.
Without using RegEx and just using Split
Note : Assuming the format is always the same
Code
var input = "asarrivalFDate=06/12/2017arrivalTDate=20/12/2017";
var result = input.Split(
new[]
{
"arrivalFDate=",
"arrivalTDate="
},
StringSplitOptions.None);
string agentName = result[0];
string arrivalFDate = result[1];
string arrivalTDate = result[2];
Console.WriteLine(agentName);
Console.WriteLine(arrivalFDate);
Console.WriteLine(arrivalTDate);
Output
as
12/6/2017
12/20/2017
I can't seem to figure this out.
I want to convert this:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
To a two dimensional array (or list) so it looks like this:
fooBarArray[0] = Array['Foo', "bar"];
fooBarArray[1] = Array['Foo', "bar"];
fooBarArray[2] = Array['Foo', "bar"];
... etc.
I have tried spliting by ("],") and then cleaning the string and creating an array afterwards. But it's just to damn UGLY!
I want a cleaner version. Is there no method built in for such a method in C#?
// Thanks
Since your question is not giving us enough information I will assume that you are trying to convert some JSON into an array of strings.
As far as I know there is no build in method in C# for this.
You could use an extension for this. Newtonsoft JSON
After installing this package you will be able to use the following code:
string foobarString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<string[][]>(foobarString);
First, split it by "[[", "], [", "]]"
var array1 = foobarString.Split(new string[] {"[[", "], [", "]]"}, StringSplitOptions.RemoveEmptyEntries);
array1 will contain "'Foo', 'bar'", "'Foo', 'bar'", "'Foo', 'bar'"
Then you can split every element by ','
var fooBarArray = array1.Select(x => x.Split(',').ToArray()).ToArray()
You can do it in one line
var fooBarArray = foobarString.Split(new string[] { "[[", "], [", "]]" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Split(',').ToArray()).ToArray()
You could use Regex to get the array elements from your source string and then convert the matches into your arrays. Something like this should do the trick:
var input = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
// search for [' more than one word character, put them into group a ',
// more than one whitespace ' more than one word character, put them into group b ']
var arrayMatches = Regex.Matches(input, #"\['(?<a>[\w]+)',\s+'(?<b>[\w]+)'\]");
var arrays = new List<string[]>();
foreach (Match arrayMatch in arrayMatches)
{
// if the match was unsuccessful, take the next match
if(!arrayMatch.Success)
continue;
// create a new string array with element in group a as first element and the element in groub b as the second one
var array = new [] {arrayMatch.Groups["a"].Value, arrayMatch.Groups["b"].Value};
arrays.Add(array);
}
// convert list to array
return arrays.ToArray();
{
const string oldString = "[['Foo', 'bar'], ['Foo', 'bar'], ['Foo', 'bar']]";
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<List<string>>>(oldString);
}
There you can find some examples. The String.Split function returns an array so you can do
string[] lines = foobarString.Split(new char[]{']'}, StringSplitOptions.RemoveEmtpyEntries);
fooBarArray[0] = lines[i].Split(new char[]{'[',']', ','}, StringSplitOptions.RemoveEmtpyEntries);
Take a look at this thread: multidimensional-array-vs
I have string COO70-123456789-12345-1. I need to parse based on the "-" not the length of the substrings and use the parsed values. I have tried using Regular expressions but having issues.Please suggest.
Also after I have split the values I need to use each values: string A = COO70, int B = 123456789, int C = 12345, short D = 1 . How do I get it in different variables A,B,C,D.
string[] results = UniqueId.Split('-');
string A = results[0];
string B = results[1];
string C = results[2];
int k_id = Convert.ToInt32(k_id);
string D = results[3];
short seq = Convert.ToInt16(seq);
string s = "COO70-123456789-12345-1";
string[] split = s.Split('-'); //=> {"COO70", "123456789", "12345", "1"}
Use indexOf
To find everything before the first hyphen use:
string original= "COO70-123456789-12345-1";
string toFirstHyphen=original.Substring(0,original.IndexOf("-"));
Or if you want every section use split like the above example.
You can verify whether the input is formatted as you want and then split to get the parts.
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = #"(?x)^(\w+-\w+-\w+-\w+)$";
Regex reg = new Regex(pattern);
string test = "word-6798-3401-001";
if((reg.Match(test).Success))
foreach (var x in test.Split(new char[] {'-'}))
Console.WriteLine(x);
}
}
So it sounds like you first want to split it, but then store it into your values.
I would do something like this:
var myString = "COO70-123456789-12345-1";
var stringSet = myString.Split("-"); // This returns an array of values.
Now we need to verify that we receive only 4 sub strings:
if (stringSet.Count != 4)
throw Exception e; // Throw a real exception, not this
From here we need to know what order our strings should be in and assign them:
var A = stringSet[0];
var B = stringSet[1];
var C = stringSet[2];
var D = stringSet[3];
While this should answer your question as posed, I would recommend you work with stringSet differently personally.
Let's consider a string like this :
string myString = "C125:AAAAA|C12:22222|C16542:D1|ABCD:1234A|C6:12AAA"
I'd like to end with something like that :
string C125 = "AAAAA";
string C12 = "22222";
string C16542 = "D1";
string C6 = "12AAA";
It means that I'd like to extract substrings (or whatever) that matches the pattern "C+characters:characters" (and exclude other patterns like ABCD:1234A e.g.). Then automatically create a variable that would have the 1st part of my "substring" ("C125:AAAAA" e.g.) as a name (so string C125 in that case) and the 2nd part of my substring as a value ("AAAAA" e.g.).
What would be the best practise to do that in C# ? Thx !
use a dictionary to store your values:
string myString = "C125:AAAAA|C12:22222|C16542:D1|ABCD:1234A|C6:12AAA";
Dictionary<string, string> result = new Dictionary<string, string>();
myString.Split('|').ToList().ForEach(x => result.Add(x.Split(':')[0], x.Split(':')[1]));
Update - improved solution from CodesInChaos:
string myString = "C125:AAAAA|C12:22222|C16542:D1|ABCD:1234A|C6:12AAA";
Dictionary<string, string> result = myString.Split('|').Select(x => x.Split(':')).ToDictionary(x => x[0], x => x[1]);
if your purpose is code-generation, you can create a StringBuilder:
string myString = "C125:AAAAA|C12:22222|C16542:D1|ABCD:1234A|C6:12AAA";
var res = myString.Split('|')
.Select(s=>s.Split(':'))
.Where(arr=>arr[0][0] == 'C')
.Aggregate(new StringBuilder(),
(b, t)=>b.AppendFormat("string {0} = \"{1}\";", t[0], t[1])
.AppendLine());
output:
string C125 = "AAAAA";
string C12 = "22222";
string C16542 = "D1";
string C6 = "12AAA";
if your purpose to store values with keys, you can create a Dictionary
string myString = "C125:AAAAA|C12:22222|C16542:D1|ABCD:1234A|C6:12AAA";
var D = myString.Split('|')
.Select(s=>s.Split(':'))
.Where(arr=>arr[0][0] == 'C')
.ToDictionary(arr=>arr[0], arr=>arr[1]);
output:
[C125, AAAAA]
[C12, 22222]
[C16542, D1]
[C6, 12AAA]
format of input string is not complex, so String.Split would more appropriate here, than RegEx
You can use the following regex, that will match any combination of word characters with length 1 or more that came after : .
#":(\w+)"
Note that the preceding pattern used capture grouping so for get the proper result you need to print the 1st group.
Demo
or you can use a positive look behind :
#"(?<=:)\w+"
Demo
But if you want to create a name from first part the better choice for such tasks is use a data structure like dictionary.
So you can loop over the result if following command :
Match match = Regex.Match(text, (\w+):(\w+));
And put the pairs of 1st and 2nd groups within a dictionary.
Perhaps, you could use something like this.You could simply use the string split.
string myString = "C125:AAAAA|C12:22222|C16542:D1|ABCD:1234A|C6:12AAA";
StringBuilder result=new StringBuilder();
List<string> resulttemp = myString.Split('|').ToList();
foreach (string[] temp in from v in resulttemp where v.StartsWith("C") select v.Split(':'))
{
result.Append("string ");
result.Append(temp[0]);
result.Append("=");
result.Append("\"");
result.Append(temp[1]);
result.Append("\"");
result.Append(";");
result.Append("\n");
}
how to extract characters until find a number in substring in asp.net c#
my string is like
NR21380
SR9956
NER6754
WR98765
SR98700
One easy way:
var firstLetterCharacters = text.TakeWhile(Char.IsLetter);
or the other way around:
var firstLetterCharacters = text.TakeWhile(c => !Char.IsDigit(c));
If you need a new string from it:
string newText = new string(firstLetterCharacters.ToArray());
You can use a regular expression to replace all non-letters:
string s=NR21380 SR9956 NER6754 WR98765 SR98700
string s2 = Regex.Replace(s, #"[^A-Z]+", String.Empty);
I just try to guess the output:
string s = "NR21380 SR9956 NER6754 WR98765 SR98700";
var list = s.Split()
.Select(x => String.Join("", x.TakeWhile(c => char.IsLetter(c))))
.ToList();
Output will be list of NR SR NER WR SR
try this
String aa = "NR21380 SR9956 NER6754 WR98765 SR98700";
//getting the first chars from the dummy string.
var firstChars= Regex.Match(aa, #"[A-Z]+");