Take only numbers from string and put in an array - c#

ok i found this for removing all 'junk' that is not a number from a string
TextIN = " 0 . 1 ,2 ; 3 4 -5 6 ,7 ,8; 9 "
string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray());
= "0123456789"
this removes all "junk" from my string leaving me just the numbers, but still how i can modify this ,
so i can have at least one delimiter for example a ' , ' b etween my numbers like "0,1,2,3,4,5,6,7,8,9" because i need to delimit this number so i can put them in an array of ints and work with them and there are not always just one digit numbers i may have 105 , 85692 etc..
any help please ?!

You can also convert to numeric values like this:
int[] numbers = Regex.Matches(textIN, "(-?[0-9]+)").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();
#L.B: agreed, but nthere might be negative values, too.

string test = string.Join(",", textIN.Where(Char.IsDigit));

For n digit numbers you can use regex.
string s = String.Join(",",
Regex.Matches(textIN,#"\d+").Cast<Match>().Select(m=>m.Value));

string justNumbers = new String(textIN.Where(Char.IsDigit).ToArray()); = "0123456789"
string[] words = justNumbers.Split(',');
will seperate the string into an array of numbers, delimited by commas.

Related

c# - Convert number in string to have certain number of digits

I have a number in string format. This number will be between 1-6 digits and i need to convert it to be filled with zeroes on left side in order to always be 6 digit number. Is there any more efficient way than this?
Int32.Parse("5").ToString("D6")
Conversion to int just feels a bit unnecessary.
You could use String.PadLeft:
string result = number.PadLeft(6, '0');
If the number can be negative this doesn't work and you need your int.Parse approach.
It is unnecessary
string result = "5".PadLeft(6,'0');
string someText = "test 5 rate";
someText = Regex.Replace(someText, #"\d+", n => n.Value.PadLeft(5, '0'));

String splitting with a special structure

I have strings of the following form:
str = "[int]:[int],[int]:[int],[int]:[int],[int]:[int], ..." (for undefined number of times).
What I did was this:
string[] str_split = str.Split(',');
for( int i = 0; i < str_split.Length; i++ )
{
string[] str_split2 = str_split[i].Split(':');
}
Unfortunately this breaks when some of the numbers have extra ',' inside a number. For example, we have something like this:
695,000:14,306,000:12,136000:12,363000:6
in which the followings are the numbers, ordered from the left to the right:
695,000
14
306,000
12
136000
12
363000
6
How can I resolve this string splitting problem?
If it is the case that only the number to the left of the colon separator can contain commas, then you could simply express this as:
string s = "695,000:14,306,000:12,136000:12,363000:6";
var parts = Regex.Split(s, #":|(?<=:\d+),");
The regex pattern, which identifies the separators, reads: "any colon, or any comma that follows a colon and a sequence of digits (but not another comma)".
A simple solution is split using : as delimiter. The resultant array will have numbers of the format [int],[int]. Parse through the array and split each entry using , as the delimiter. This will give you an array of [int] numbers.
It might not be the best way to do it and it might not work all the time but here's what I'd do.
string[] leftRightDoubles = str.Split(':');
foreach(string substring in leftRightDoubles){
string[] indivNumbers = str.Split(',');
//if indivNumbers.Length == 2, you know that these two are separate numbers
//if indivNumbers.Length > 2, use heuristics to determine which parts belong to which number
if(indivNumbers.Length > 2) {
for(int i = 0, i < indivNumbers.Length, i++) {
if(indivNumbers[i] != '000') { //Or use some other heuristic
//It's a new number
} else {
//It's the rest of previous number
}
}
}
}
//It's sort of pseudocode with comments (haven't touched C# in a while so I don't want to write full C# code)

How can i find the cardinal of the intersection, character wise, between two strings?

I am working on a project that requires some string manipulation and i need some help.
Say i have two strings:
string1 = "1 2 3 4 5";
string2 = "1 2 4 6 7";
This is actually what most of the strings I will be working with look like.
I would like to know what is a smart, modern method, if any, to find the number of intersection between string of this type, something idealy like this:
//a way to create GetCardinal is what I am looking for
int cardinal = GetCardinal(string1, string2);
//Cardinal should be 3 as the intersection is "1 2 4"
I am mainly interested in methods that work great for the type of inputs like string1 and string2, meaning sequences of numbers separated by blank spaces
The reason for not using a List of int's is because the strings are output values and I am expecting some character outputs as well.
Thank you,
Ciprian
You have to split them by white-space, then you can use Intersect + Count:
int cardinal = string1.Split().Intersect(string2.Split()).Count();
String.Split, String.Join and a little bit of LINQ (Intersect) will do the job:
var result = String.Join(" ", string1.Split(' ').Intersect(string2.Split(' ')));
If you just need number of elements in the intersection, use Count:
var cardinal = string1.Split(' ').Intersect(string2.Split(' ')).Count();
You can use the split function of string plus some Linq
int GetCardinal(string s1, string s2)
{
return s1.Split(' ').Intersect(s2.Split(' ')).Count();
}
or if you could have multiple spaces or tabs:
int GetCardinal(string s1, string s2)
{
char []separators = new char[] { ' ', '\t' };
return s1.Split(separators, StringSplitOptions.RemoveEmptyEntries).Intersect(s2.Split(separators, StringSplitOptions.RemoveEmptyEntries)).Count();
}

extract numbers and alpha into two strings

Suppose I have a string that looks like this "dentist: 800-483-9767" or this "john (232)233-2323" or some other combination that has numbers, letters and other types of characters, and that's max 25 characters long. I want to extract the digits and letters characters into 2 strings so that I get this:
string digits = "8004839767";
string letters = "dentist";
What's the best what to do this?
Thanks
You can use Linq and char.IsDigit, char.IsLetter
string input = "dentist: 800-483-9767";
string digits = new string(input.Where(char.IsDigit).ToArray());
string letters = new string(input.Where(char.IsLetter).ToArray());
Result:
input = "dentist: 800-483-9767";
digits = "8004839767"
letters = "dentist"
input = "john (232)233-2323";
digits = "2322332323"
letters = "john"
If it really is about getting digits and letters (and not splitting somewhere, matching a phone number or someting similar), this would be my attempt:
var input = "dentist: 0800-483-9767";
var digits = string.Join(string.Empty, input.Where(char.IsDigit));
var letters = string.Join(string.Empty, input.Where(char.IsLetter));
string input = "dentist: 800-483-9767";
string[] split = input.Split(':');
string letters = split[0];
string digits = split[1].Replace("-","").Trim();
Similar to what juergen d posted, however, it will remove the dashes in the number.
When saying "looks like", you should be more specific about what can change and what cannot.
If the format is always :, you can do
Data process(String input)
{
var elements = input.Split(new char[] {':'});
Data result;
result.letters = elements[0].Trim();
result.digits = elements[1].Trim().Replace("-", "");
return result;
}
That's exactly the kind of unprecision I was talking about.
If you are sure that the letters won't contain numbers, you can use a regular expression to separate the letters from the rest. If you are sure that the letters won't contain spaces, you can Split(' '). I mean, could it be john 2 232:233-2323, where "john 2" is the name, and the rest is a number.
If you want to parse it, the first thing you have to do is to identify some kind of format.
If the name won't contain spaces, then just call Split(' ', 2), take the first thing as the name, and remove everything that is not a number from the second one with a regular expression. I've never used regexp in C# before, but I think it should be Regex.Replace(input, "[^\\d]+", "", RegexOptions.None).

Looking for the simplest way to extract tow strings from another in C#

I have the following strings:
string a = "1. testdata";
string b = "12. testdata xxx";
What I would like is to be able to extract the number into one string and the characters following the number into another. I tried using .IndexOf(".") and then remove, trim and
substrings. If possible I would like to find something simpler as I have this to do in a
lot of parts of my code.
if the format is always the same you could do:
a.Split('.');
Proposed solutions so far are not correct.
First, after Split('.') or Split(".") you will have space in the beginning of second substring.
Second, if you have more than one dot - you'll have to do something yet after the split.
More robust solution is below:
string a = "11. Test string. With dots.";
var res = a.Split(new[] {". "}, 2, StringSplitOptions.None);
string number = res[0];
string val = res[1];
Argument 2 specifies maximum number of strings to return. Thus when you have several dots - it will make a split only at the first.
string[]list = a.Split(".");
string numbers = list[0];
string chars = list[1];

Categories