how to split a string based on integers occurrence? [duplicate] - c#

This question already has answers here:
How to get the last five characters of a string using Substring() in C#?
(12 answers)
Closed 4 years ago.
If a string that contains integers and I want to split it based on integers occurrence. how to do that?
string test= "a b cdf 7654321;
then I want to store the integer and all words before it, like this
string stringBefore="";
// the integer will be last item
string integer="";
Note:
in my case the integer always will be 7 digits

You can use Regex.Split with a capture group to return the delimiter:
var ans = Regex.Split(test, #"("\d{7})");
If the number is at the end of the string, this will return an extra empty string. If you know it is always at the end of the string, you can split on its occurrence:
var ans = Regex.Split(test, #"(?=\d{7})");

According to your comments the integer is always 7 digits and it is always the last item of the string.
In that case, just use Substring()
string test = "a b cdf 7654321";
string stringBefore = test.Substring(0, test.Length - 7);
string integer = test.Substring(test.Length - 7);
Substring just makes a string based on a portion of your original string.
EDIT
I was a little surprised to find there wasn't a built in way to easily split a string in to two strings based on an index (maybe I missed it). I came up with a LINQ extension method that achieves what I was trying to do, maybe you will find it useful:
public static string[] SplitString(this string input, int index)
{
if(index < 0 || input.Length < index)
throw new IndexOutOfRangeException();
return new string[]
{
String.Concat(input.Take(input.Length - index)),
String.Concat(input.Skip(input.Length - index))
};
}
I think I would rather use a ValueTuple if using C# 7, but string array would work too.
Fiddle for everything here

Related

How to find the immediate integer value written before a string? [duplicate]

This question already has answers here:
How to get the digits before some particular word using regex in c#?
(8 answers)
Closed 2 years ago.
How to find the immediate integer value written before a string in c#? For example
50+ boxes were ordered, however only 2 are delivered.
I need to know the number of boxes (integer value) written just before "delivered". The output should be 2. I have written a code in c# using Regex:
string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, #"\d+").Value;
//The output I get is 50 instead of 2.
To get the last number that is followed by the word "delivered", you may use the following pattern:
\b\d+\b(?=[^\d]*\bdelivered\b)
Regex demo.
Here's a full example:
string line = "50+ boxes were ordered, however only 2 are delivered.";
var match = Regex.Match(line, #"\b\d+\b(?=[^\d]*\bdelivered\b)");
if (match.Success)
{
string boxesDelivered = match.Value;
// TODO: convert the value to a numeric type or use it as is.
}
Try it online.
written just before delivered
I'm going to take that verbatim as your user requirement - find the last number in the string that appears before "delivered".
You can use (\d+)[^\d]*(?:delivered), which says "match any sequence of numbers that does not occur before another sequence of numbers and does occur before delivered".
string line = "50+ boxes were ordered, however only 2 are delivered.";
string boxesDelivered = Regex.Match(line, #"(\d+)[^\d]*(?:delivered)").Groups[1].Value;
// boxesDelivered = 2

c# Leave last 3 letters in a string [duplicate]

This question already has answers here:
Extract only right most n letters from a string
(22 answers)
Closed 2 years ago.
How to remove letters from the string and leave just 3 last chars
Input:
foobar
Output:
bar
I tried:
string.Concat("foobar".Reverse().Skip(3).Reverse());
But that removes last 3 lines not keeps them
Well, you can try Substring: if source is long enough we get Substring otherwise leave source intact:
string source = ...
string result = source.Length > 3
? source.Substring(source.Length - 3)
: source;
Or even
string result = source.Substring(Math.Max(0, source.Length - 3));
Since C# 8, you can also use range syntax:
string result = source.Length > 3 ? source[^3..] : source;
or:
string result = source[^Math.Min(3, source.Length)..];
[^3..] is a range which means "start 3 elements from the end, and keep going until the end".
There is a one line solution as well. Just check whether source string has enough length to get last 3 characters using Substring or leave string as is. Math.Max function will return a correct index
var str = "foobar";
var result = str.Substring(Math.Max(0, str.Length - 3));

getting numbers from a string c# [duplicate]

This question already has answers here:
Using regex to extract multiple numbers from strings
(4 answers)
Closed 5 years ago.
I have an input string like below:
"/myWS/api/Application/IsCarAvailable/123456/2017"
It is the end of a Web API call that I am making. I need to easily extract the 123456 from the URL.
I was hoping something like the below would work
string[] numbers = Regex.Split(input, #"\D+");
However, when I set a breakpoint on numbers and run the code it is showing an array of 3 elements?
Element at [0] is ""
Element at [1] is 123456
Element at [2] is 2017
Does anyone see why it would be getting the empty string as the first element?
I suggest matching, not splitting:
string source = #"/myWS/api/Application/IsCarAvailable/123456/2017";
string[] numbers = Regex
.Matches(source, "[0-9]+")
.OfType<Match>()
.Select(match => match.Value)
.ToArray();
Please, notice that \d+ in .Net means any unicode digits (e.g. Persian ones: ۰۱۲۳۴۵۶۷۸۹): that's why I put [0-9]+ pattern (RegexOptions.ECMAScript is an alternative if \d+ pattern is preferrable).
If your string is always in the same format, this would work:
string numbers = input.Split('/')[input.Split('/').Length - 2];
I think this is because the split method "splits" the string at the matching expression. So the empty string is the part before the first match.
Any reason why you would not use Regex.Matches(input,"\\d+") instead?
string numtest = "http://www.google.com/test/123456/7890";
var matchResult = Regex.Matches(numtest, "\\d+");
for (int i = 0; i < matchResult.Count; i++)
Console.WriteLine($"Element {i} is {matchResult[i].Value}");
Hope that helps. Regards!

Replacing specific parts of a string in an array

I'm pretty familiar with finding and replacing things in an array, but I'm having trouble finding out how to replace specific parts of a string. For instance, say the first item in my array is a string of sixteen random numbers like 1786549809654768. How would I go about replacing the first twelve characters with x's for example?
Because string can be translated to and from an array of char you could easily transform your problem into replace things in an array problem:
char[] characters = input.ToCharArray();
// do your replace logic here
string result = new string(characters);
Or you could use Substring. Assuming n is number of characters you want to replace from the beginning or the string:
string result = new string('x', n) + input.Substring(n);
You can use Linq:
String test = "1234123412341234";
string output = new String(test.Select((c, index) => index < 12 ? 'x' : c).ToArray());
Console.WriteLine(output);
//xxxxxxxxxxxx1234

Extract number from end of string [duplicate]

This question already has answers here:
Find and extract a number from a string
(32 answers)
Closed 8 years ago.
I have some strings like "pan1", "pan2", and "pan20" etc. I need to extract number. I use it:
char ch = s[(s.Length) - 1];
int n = Convert.ToInt32(Char.GetNumericValue(ch));
But in case of, for example, "pan20" the result is not correct 0.
Index Approach
if you know where is the starting index of the number then simply you can do this :
string str = "pan20";
int number = Convert.ToInt32(str.Substring(3));
Note that "3" is the starting index of the number.
Fixed Prefix Approach
try to remove "pan" from the string; like this
string str = "pan20";
int number = Convert.ToInt32(str.Replace("pan", ""));
Regular Expression Approach
use regular expression only when string contains undetermined text inside
string str = "pan20";
int number = Convert.ToInt32(System.Text.RegularExpressions.Regex.Match(str, #"\d+").Value;
You can use for example regular expressions, for example [0-9]+$ to get the numbers in the end. See the Regex class in MSDN.

Categories

Resources