I got a string
string newString = "[17, Appliance]";
how can I put the 17 and Appliance in two separate variables while ignoring the , and the [ and ]?
I tried looping though it but the loop doesn't stop when it reaches the ,, not to mention it separated 1 & 7 instead of reading it as 17.
For example, you could use this:
newString.Split(new[] {'[', ']', ' ', ','}, StringSplitOptions.RemoveEmptyEntries);
This is another option, even though I wouldn't go with it, especially if you might have more than one [something, anothersomething] in the string.
But there you go:
string newString = "assuming you might [17, Appliance] have it like this";
int first = newString.IndexOf('[')+1; // location of first after the `[`
int last = newString.IndexOf(']'); // location of last before the ']'
var parts = newString.Substring(first, last-first).Split(','); // an array of 2
var int_bit = parts.First ().Trim(); // you could also go with parts[0]
var string_bit = parts.Last ().Trim(); // and parts[1]
This may not be the most performant method, but I'd go with it for ease of understanding.
string newString = "[17, Appliance]";
newString = newString.Replace("[", "").Replace("]",""); // Remove the square brackets
string[] results = newString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries); // Split the string
// If your string is always going to contain one number and one string:
int num1 = int.Parse(results[0]);
string string1 = results[1];
You'd want to include some validation to ensure your first element is indeed a number (use int.TryParse), and that there are indeed two elements returned after you split the string.
Related
Okay, lets say I have a string:
string text = "one|two|three";
If I do string[] texts = text.Split('|'); I will end up with a string array of three objects. However, this isn't what I want. What I actually want is to split the string only once... so the two arrays I could would be this:
one
two|three
Additionally, is there a way to do a single split with the last occurrence in a string? So I get:
one|two
three
As well, is there a way to split by a string, instead of a character? So I could do Split("||")
Split method takes a count as parameter, you can pass 2 in that position, which basically says that you're interested in only 2 elements maximum. You'll get the expected result.
For second question: There is no built in way AFAIK. You may need to implement it yourself by splitting all and joining first and second back.
C#'s String.Split() can take a second argument that can define the number of elements to return:
string[] texts = text.Split(new char[] { '|' }, 2);
For your first scenario, you can pass a parameter of how many strings to split into.
var text = "one|two|three";
var result = text.Split(new char[] { '|' }, 2);
Your second scenario requires a little more magic.
var text = "one|two|three";
var list = text.Split('|');
var result = new string[] { string.Join("|", list, 0, list.Length - 1), list[list.Length - 1] };
Code has not been verified to check results before using.
Well, I took it as a challenge to do your second one in one line. The result is... not pretty, mostly because it's surprisingly difficult to reverse a string and keep it as a string.
string text = "one|two|three";
var result = new String(text.Reverse().ToArray()).Split(new char[] {'|'}, 2).Reverse().Select(c => new String(c.Reverse().ToArray()));
Basically, you reverse it, then follow the same procedure as the first one, then reverse each individual one, as well as the resulting array.
You can simply do like this as well...
//To split at first occurence of '|'
if(text.Containts('|')){
beginning = text.subString(0,text.IndexOf('|'));
ending = text.subString(text.IndexOf('|');
}
//To split at last occurence of '|'
if(text.Contains('|')){
beginning = text.subString(0,text.LastIndexOf('|'));
ending = text.subString(text.LastIndexOf('|');
}
Second question was fun. I solved it this way:
string text = "one|two|three";
var result =
new []
{
string.Concat(text.ToCharArray().TakeWhile((c, i) => i <= text.LastIndexOf("|"))),
string.Concat(text.ToCharArray().SkipWhile((c, i) => i <= text.LastIndexOf("|")))
};
I read strings from a file and they come in various styles:
item0 item1 item2
item0,item1,item2
item0_item1_item2
I split them like this:
string[] split_line = line[i].split(new char[] {' ',',','_'});
I change an item (column) and then i stitch the strings back together using string builder.
But now when putting the string back I have to use the right delimiter.
Is it possible to know which delimiter was used when splitting the string?
UPDATE
the caller will pass me the first item so that I only change that line.
Unless you keep track of splitting action (one at the time) you don't.
Otherwise, you could create a regular expression, to catch the item and the delimiter and go from there.
Instead of passing in an array of characters, you can use a Regex to split the string instead. The advantage of doing this, is that you can capture the splitting character. Regex.Split will insert any captures between elements in the array like so:
string[] space = Regex.Split("123 456 789", #"([,_ ])");
// Results in { "123", " ", "456", " ", "789" }
string[] comma = Regex.Split("123,456,789", #"([,_ ])");
// Results in { "123", ",", "456", ",", "789" }
string[] underscore = Regex.Split("123_456_789", #"([,_ ])");
// Results in { "123", "_", "456", "_", "789" }
Then you can edit all items in the array with something like
for (int x = 0; x < space.Length; x += 2)
space[x] = space[x] + "x";
Console.WriteLine(String.Join("", space));
// Will print: 123x 456x 789x
One thing to be wary of when dealing with multiple separators is if there are any lines that have spaces, commas and underscores in them. e.g.
37,hello world,238_3
This code will preserve all the distinct separators but your results might not be expected. e.g. the output of the above would be:
37x,hellox worldx,238x_3x
As I mentioned that the caller passes me the first item so I tried something like this:
// find the right row
if (lines[i].ToLower().StartsWith(rowID))
{
// we have to know which delim was used to split the string since this will be
// used when stitching back the string together.
for (int delim = 0; delim < delims.Length; delim++)
{
// we split the line into an array and then use the array index as our column index
split_line = lines[i].Trim().Split(delims[delim]);
// we found the right delim
if (split_line.Length > 1)
{
delim_used = delims[delim];
break;
}
}
}
basically I iterate each line over the delims and check the resulting array length. If it is > 1 that means that delim worked otherwise skip to next one. I am using split functions property "If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance."
I have a string with the following text:
:0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:
How do I parse the final number? i.e.:
194176015020283762507
You should first use String.Split() to separate the string by the colon (':') separators. Then access the correct element.
var input = ":0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:";
var split = input.Split(':');
var final = split[3];
Note that by default, Split() keeps empty entries. You will have one at the beginning and end, because of the initial and ending colons. You could also use:
var split = input.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries);
var final = split[2];
which, as the option implies, removes empty entries from the array. So your number would be at index 2 instead of 3.
string str = ":0c4b7fcdffc38322555a9e35c22c9469:Nick:194176015020283762507:";
string num = str.Split(':')[3];
var finalNumber = input.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)
.Last()
This code will split your input string into strings, separated by : (empty strings are removed from start and end of sequence). And last string is returned, which is your finalNumber.
My string is like this:
string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
Here actually I want to extract the last word, 'API', and return.
What would be the C# code to do the above extraction?
Well, the naive implementation to that would be to simply split on each space and take the last element.
Splitting is done using an instance method on the String object, and the last of the elements can either be retrieved using array indexing, or using the Last LINQ operator.
End result:
string lastWord = input.Split(' ').Last();
If you don't have LINQ, I would do it in two operations:
string[] parts = input.Split(' ');
string lastWord = parts[parts.Length - 1];
While this would work for this string, it might not work for a slightly different string, so either you'll have to figure out how to change the code accordingly, or post all the rules.
string input = ".... ,API";
Here, the comma would be part of the "word".
Also, if the first method of obtaining the word is correct, that is, everything after the last space, and your string adheres to the following rules:
Will always contain at least one space
Does not end with one or more spaces (in case of this you can trim it)
Then you can use this code that will allocate fewer objects on the heap for GC to worry about later:
string lastWord = input.Substring(input.LastIndexOf(' ') + 1);
However, if you need to consider commas, semicolons, and whatnot, the first method using splitting is the best; there are fewer things to keep track of.
First:
using System.Linq; // System.Core.dll
then
string last = input.Split(' ').LastOrDefault();
// or
string last = input.Trim().Split(' ').LastOrDefault();
// or
string last = input.Trim().Split(' ').LastOrDefault().Trim();
var last = input.Substring(input.LastIndexOf(' ')).TrimStart();
This method doesn't allocate an entire array of strings as the others do.
string workingInput = input.Trim();
string last = workingInput.Substring(workingInput.LastIndexOf(' ')).Trim();
Although this may fail if you have no spaces in the string. I think splitting is unnecessarily intensive just for one word :)
static class Extensions
{
private static readonly char[] DefaultDelimeters = new char[]{' ', '.'};
public string LastWord(this string StringValue)
{
return LastWord(StringValue, DefaultDelimeters);
}
public string LastWord(this string StringValue, char[] Delimeters)
{
int index = StringValue.LastIndexOfAny(Delimeters);
if(index>-1)
return StringValue.Substring(index);
else
return null;
}
}
class Application
{
public void DoWork()
{
string sentence = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
string lastWord = sentence.LastWord();
}
}
var lastWord = input.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Last();
string input = "STRIP, HR 3/16 X 1 1/2 X 1 5/8 + API";
var a = input.Split(' ');
Console.WriteLine(a[a.Length-1]);
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];