How to separate a string into different substrings without known format - c#

I am having trouble with this.
I have couple of strings like this [44, 74, 57]
Now I want to separate into 3 strings and omit the brackets and commas in C#, the output would be like this:
44
74
57
I have tried substring, concate, Regular expression but the problem is the strings, they don't have the same number of digits or format [xx, yy, zz]
Some strings are like [44, 74, 57], others are like [42, 6653, 40000]
Can anyone help me what should I use?

As long as the []'s and the ,'s are strongly consistent the number of digits will be irrelevant and Split should work:
string tempstr = "[44, 74, 57]";
string[] outarray = tempstr.Split("[,] ".ToArray(),StringSplitOptions.RemoveEmptyEntries);

the string in your questions appears to be a JSON string. if this is the case then
use json deserialiser instead. One good options is Newtonsoft.Json
and you can have the numbers as an int array by using the command
var array JsonConvert.DesrializeObject<int[]>("[1,2,3]");

string s = "[22, 4564, 65]";
string result[] = s.Replace('[', '').Replace(']', '').Split(',');

brute force regex /\[(\d)+, ?(\d+), ?(\d+)\]/ data will be captured in groups 1, 2 and 3 cc: http://rubular.com/r/eheSoJFJ8q
Or using replace and split
char[] delimiterChars = { ', ', ',' };
string text = "[1, 2,333]";
string[] words = text.Replace('[','').Replace(']','').Split(comma);
System.Console.WriteLine("just the numbers {0}:", words);

String s = "[11,12,23]";
String[] s1 = s.Substring(1, s.Length - 2).Split(',');
s1 will have 3 arrays containing three numbers.

string tempstr = "[44, 74, 57]";
tempstr=tempstr.Remove(']').Remove('[');
string[] outarray =tempstr.Split(",");

Try to remove the brackets
Then split the string by comma.
You will end up with an array of the values you were expecting.
String value=[44,74,57,444,555];
Value=value.replace("[","");
Value=value.replace("]","");
String[] allValues=value.split(new char[]{','});
Now the array should contain all the values from your string.
That is mostly pseudo code. I wrote this on a tablet.
Hope it helps.

Related

Need to create a Regular expression to Split String after first \r\n

I have been stuck in a situation .
Here are few input strings -
"abacuses\r\n25"
"alphabet\r\n56,\r\n57"
"animals\r\n44,\r\n45,\r\n47"
I need the output to be splited like -
"abacuses\r\n25" to be splitted into A)abacuses B)25
"alphabet\r\n56,\r\n57" to be splitted into A)alphabet B)56,57
"animals\r\n44,\r\n45,\r\n47" to be splitted into A)animals B)44,45,47
So far I have tried this but it doesn't work-
string[] ina = Regex.Split(indexname, #"\r\n\D+");
string[] ina = Regex.Split(indexname, #"\r\n\");
Please Help
No regex needed in your example. You basicaly parse string:
string input = "animals\r\n44,\r\n45,\r\n47";
var split = input.Split(new char[]{'\r','\n',','}, StringSplitOptions.RemoveEmptyEntries);
var name = split[0]; //animals
var args = string.Join(",", split.Skip(1)); //44,45,37
Many people use it for parsing, but Regex is not a parsing language! It is pattern matcher! It is used to find substrings in string! If you can just Split your string - just do it, really. It is much easier to understand than Regex expression.
If you need to split a string at the first \r\n, you may use a String.Split with a count argument:
var line = "animals\r\n44,\r\n45,\r\n47";
var res = line
.Split(new[] {"\r\n"}, 2, StringSplitOptions.RemoveEmptyEntries);
// Demo output
Console.WriteLine(res[0]);
if (res.GetLength(0) > 1)
Console.WriteLine(res[1].Replace("\r\n", "")); // In the second value, linebreaks should be removed
See the C# demo
The 2 in .Split(new[] {"\r\n"}, 2, StringSplitOptions.RemoveEmptyEntries) means that the whole string should be split into 2 parts only and since the string is processed from left to right, the split will occur on the first "\r\n" substring found.

how to replace one/multiple spaces into a deliminator using C#

Now I'm parsing a text, I want to split and add one by one
But first thing first, the best way is to replace multiple spaces with one unique deliminator
Below is the sample target text:
Total fare 619,999.0d-
12 11 82139 09/13/2013 D 103,500.00 2/025189 PARK LA000137
09/13/2013 D 50.00 File Ticket - PS1309121018882/
Can anybody know how to handle it in C#?
the best way is to replace multiple spaces with one unique
deliminator
Not really sure if its the best way, but following works, without REGEX
string newStr = string.Join(":",
str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
try
var strings = text.Split(' ').Where(str => str.Length > 0);
You can use a regular expression:
string delimiter = ":";
var whiteSpaceNormalised = Regex.Replace(input, #"\s+", delimiter);
Use regular expressions instead, replace more than one occurrence of space with single space
string parsedText = System.Text.RegularExpressions.Regex.Replace(inputString,"[ ]+"," ");

Regex + Convert line of numbers separated by white space into array

I'm trying to convert a string that contains multiple numbers, where each number is separated by white space, into a double array.
For example, the original string looks like:
originalString = "50 12.2 30 48.1"
I've been using Regex.Split(originalString, #"\s*"), but it's returning an array that looks like:
[50
""
12
"."
2
""
...]
Any help is much appreciated.
Using this instead
originalString.Split(new char[]{'\t', '\n', ' ', '\r'}, StringSplitOptions.RemoveEmptyEntries);
No need to rush RegEx everytime :)
What about string[] myArray = originalString.Split(' ');
I don't see the need for a RegEx here..
If you really want to use a RegEx, use the pattern \s+ instead of \s*.
The * means zero or more, but you want to split on one or more space character.
Working example with a RegEx:
string originalString = "50 12.2 30 48.1";
string[] arr = Regex.Split(originalString, #"\s+");
foreach (string s in arr)
Console.WriteLine(s);
Regex.Split(originalString, #"\s+").Where(s => !string.IsNullOrWhiteSpace(s))
The Where returns an IEnumerable with the null/whitespace filtered out. if you want it as an array still, then just add .ToArray() to that chain of calls.
The + character is necessary because you need a MINIMUM of one to make this a correct match.
I would stick with String.Split, supplying all whitespace characters that you are expecting.
In regular expressions, \s is equivalent to [ \t\r\n] (plus some other characters specific to the flavour in use); we can represent these through a char[]:
string[] nums = originalString.Split(
new char[] { ' ', '\t', '\r', '\n' },
StringSplitOptions.RemoveEmptyEntries);
The default behaviour if you pass null as a separator to String.Split is to split on whitespace. That includes anything that matches the Unicode IsWhiteSpace test. Within the ASCII range that means tab, line feed, vertical tab, form feed, carriage return and space.
Also you can avoid empty fields by passing the RemoveEmptyEntries option.
originalString = "50 12.2 30 48.1";
string[] fields = originalString.Split(null as char[], StringSplitOptions.RemoveEmptyEntries);

split a string in to multiple strings

123\r\n456t\r\n789
How can i split the string above in to multiple strings based on the string text
.split has only over load that takes char :(
string.Split has supported an overload taking an array of string delimiters since .NET 2.0. For example:
string data = "123text456text789";
string[] delimiters = { "text" };
string[] pieces = data.Split(delimiters, StringSplitOptions.None);
use string.split("text"), hope it will help.
I believe you want to split 123, 456, 789 as you have \r\n after them.
Easiest way I see is
string textVal = "123\r\n456t\r\n789";
textVal = textVal.replace("\r", "").replace("\n",",");
string arrVal[] = textVal.split(',');
Now you have arrVal containing 123, 456, 789.
Happy coding
String.Split supports also an array of strings. In your case you can do:
string s = "123\r\n456t\r\n789";
string[] parts = s.Split(new string[] {"\r\n"}, StringSplitOptions.None);

Extract substring from a string until finds a comma

I'm building a page and would like to know how to extract substring from a string until finds a comma in ASP.Net C#. Can someone help please?
substring = str.Split(',')[0];
If str doesn't contain any commas, substring will be the same as str.
EDIT: as with most things, performance of this will vary for edge cases. If there are lots and lots of commas, this will create lots of String instances on the heap that won't be used. If it is a 5000 character string with a comma near the start, the IndexOf+Substring method will perform much better. However, for reasonably small strings this method will work fine.
var firstPart = str.Split(new [] { ',' }, 2)[0]
Second parameter tells maximum number of parts. Specifying 2 ensures performance is fine even if there are lots and lots of commas.
You can use IndexOf() to find out where is the comma, and then extract the substring. If you are sure it will always have the comma you can skip the check.
string a = "asdkjafjksdlfm,dsklfmdkslfmdkslmfksd";
int comma = a.IndexOf(',');
string b = a;
if (comma != -1)
{
b = a.Substring(0, comma);
}
Console.WriteLine(b);
myString = myString.Substring(0,myString.IndexOf(','));
Alina, based on what you wrote above, then Split will work for you.
string[] a = comment.Split(',');
Given your example string, then a[0] = "aaa", a[1] = "bbbbb", a[2] = "cccc", and a[3] = "dddd"
string NoComma = "";
string example = "text before first comma, more stuff and another comma, there";
string result = example.IndexOf(',') == 0 ? NoComma : example.Split(',')[0];

Categories

Resources