Converting a string number into sequence of digits - .Net 2.0 - c#

Given a string
string result = "01234"
I want to get the separate integers 0,1,2,3,4 from the string.
How to do that?
1
The following code is giving me the ascii values
List<int> ints = new List<int>();
foreach (char c in result.ToCharArray())
{
ints.Add(Convert.ToInt32(c));
}

EDIT: I hadn't spotted the ".NET 2.0" requirement. If you're going to do a lot of this sort of thing, it would probably be worth using LINQBridge, and see the later bit - particularly if you can use C# 3.0 while still targeting 2.0. Otherwise:
List<int> integers = new List<int>(text.Length);
foreach (char c in text)
{
integers.Add(c - '0');
}
Not as neat, but it will work. Alternatively:
List<char> chars = new List<char>(text);
List<int> integers = chars.ConvertAll(delegate(char c) { return c - '0'; });
Or if you'd be happy with an array:
char[] chars = text.ToCharArray();
int[] integers = Arrays.ConvertAll<char, int>(chars,
delegate(char c) { return c - '0'; });
Original answer
Some others have suggested using ToCharArray. You don't need to do that - string already implements IEnumerable<char>, so you can already treat it as a sequence of characters. You then just need to turn each character digit into the integer representation; the easiest way of doing that is to subtract the Unicode value for character '0':
IEnumerable<int> digits = text.Select(x => x - '0');
If you want this in a List<int> instead, just do:
List<int> digits = text.Select(x => x - '0').ToList();

Loop the characters and convert each to a number. You can put them in an array:
int[] digits = result.Select(c => c - '0').ToArray();
Or you can loop through them directly:
foreach (int digit in result.Select(c => c - '0')) {
...
}
Edit:
As you clarified that you are using framework 2.0, you can apply the same calculation in your loop:
List<int> ints = new List<int>(result.Length);
foreach (char c in result) {
ints.Add(c - '0');
}
Note: Specify the capacity when you create the list, that elliminates the need for the list to resize itself. You don't need to use ToCharArray to loop the characters in the string.

You could use LINQ:
var ints = result.Select(c => Int32.Parse(c.ToString()));
Edit:
Not using LINQ, your loop seems good enough. Just use Int32.Parse instead of Convert.ToInt32:
List<int> ints = new List<int>();
foreach (char c in result.ToCharArray())
{
ints.Add(Int32.Parse(c.ToString()));
}

string result = "01234";
List<int> list = new List<int>();
foreach (var item in result)
{
list.Add(item - '0');
}

Index into the string to extract each character. Convert each character into a number. Code left as an exercise for the reader.

another solution...
string numbers = "012345";
List<int> list = new List<int>();
foreach (char c in numbers)
{
list.Add(int.Parse(c.ToString()));
}
no real need to do a char array from the string since a string can be enumerated over just like an array.
also, the ToString() makes it a string so the int.Parse will give you the number instead of the ASCII value you get when converting a char.

List<int> ints = new List<int>();
foreach (char c in result.ToCharArray())
{
ints.Add(Convert.ToInt32(c));
}

static int[] ParseInts(string s) {
int[] ret = new int[s.Length];
for (int i = 0; i < s.Length; i++) {
if (!int.TryParse(s[i].ToString(), out ret[i]))
throw new InvalidCastException(String.Format("Cannot parse '{0}' as int (char {1} of {2}).", s[i], i, s.Length));
}
return ret;
}

Related

How do I add integers to char[] array?

So I have to write a code that picks our random numbers from 1 to 100 and add them to a char[] array. But I'm having some difficulty doing so as I can only add the numbers to the array if I convert them to a char using (char) which changes the number. Can someone please help me?
Thanks,
public char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 101));
}
return l;
}
use ToChar() method of Convert class.
Convert.ToChar(new Random().Next(1, 101))
You cannot convert an integer larger then 9 into a char because it's considered as 2 chars, i.e. 10 will be considered as 1 and 0.
so I would recommend adding it to an array of strings
(except if your trying to get a random charcode which I dont think is the case, because why till 100?)
Personally, I'd use an int[] array instead
There shouldn't be any problem in storing ints up to 65535 in a char but you will have to cast it back to an int if you don't want it to be weird:
public static void Main()
{
var x = CreationListe(200);
foreach(var c in x)
Console.WriteLine((int)c); //need to cast to int!
}
public static char[] CreationListe(int nmbrevaleurTirés)
{
char[] l = new char[nmbrevaleurTirés];
for (int i = 0; i < nmbrevaleurTirés; i++)
{
l[i] = (char)(new Random().Next(1, 65536));
}
return l;
}
https://dotnetfiddle.net/z5yoBn
If you don't cast it back to int, then you'll get the char at that character index in the unicode table. If you've put 65 into a char, you'll get A when you print it, for example. This is because A is at position 65 in the table:
(ASCII table image posted for brevity's sake)

Detecting and modifying ListBox entries that contain digits

My program has about 25 entries, most of them string only. However, some of them are supposed to have digits in them, and I don't need those digits in the output (output should be string only). So, how can I "filter out" integers from strings?
Also, if I have integers, strings AND chars, how could I do it (for example, one ListBox entry is E#2, and should be renamed to E# and then printed as output)?
Assuming that your entries are in a List<string>, you can loop through the list and then through each character of each entry, then check if it is a number and remove it. Something like this:
List<string> list = new List<string>{ "abc123", "xxx111", "yyy222" };
for (int i = 0; i < list.Count; i++) {
var no_numbers = "";
foreach (char c in list[i]) {
if (!Char.IsDigit(c))
no_numbers += c;
}
list[i] = no_numbers;
}
This only removes digits as it seems you wanted from your question. If you want to remove all other characters except letters, you can change the logic a bit and use Char.IsLetter() instead of Char.IsDigit().
You can remove all numbers from a strings with this LINQ solution:
string numbers = "Ho5w ar7e y9ou3?";
string noNumbers = new string(numbers.Where(c => !char.IsDigit(c)).ToArray());
noNumbers = "How are you?"
But you can also remove all numbers from a string by using a foreach loop :
string numbers = "Ho5w ar7e y9ou3?";
List<char> noNumList = new List<char>();
foreach (var c in numbers)
{
if (!char.IsDigit(c))
noNumList.Add(c);
}
string noNumbers = string.Join("", noNumList);
If you want to remove all numbers from strings inside a collection :
List<string> myList = new List<string>() {
"Ho5w ar7e y9ou3?",
"W9he7re a3re y4ou go6ing?",
"He2ll4o!"
};
List<char> noNumList = new List<char>();
for (int i = 0; i < myList.Count; i++)
{
foreach (var c in myList[i])
{
if(!char.IsDigit(c))
noNumList.Add(c);
}
myList[i] = string.Join("", noNumList);
noNumList.Clear();
}
myList Output :
"How are you?"
"Where are you going?"
"Hello!"
I don't know exactly what is your scenario, but given a string, you can loop through its characters, and if it's a number, discard it from output.
Maybe this is what you're looking for:
string entry = "E#2";
char[] output = new char[entry.Length];
for(int i = 0, j =0; i < entry.Length ; i++)
{
if(!Char.IsDigit(entry[i]))
{
output[j] = entry[i];
j++;
}
}
Console.WriteLine(output);
I've tried to give you a simple solution with one loop and two index variables, avoiding string concatenations that can make performance lacks.
See this example working at C# Online Compiler
If i am not wrong,maybe this is how your list looks ?
ABCD123
EFGH456
And your expected output is :
ABCD
EFGH
Is that correct?If so,assuming that it's a List<string>,then you can use the below code :
list<string> mylist = new list<string>;
foreach(string item in mylist)
{
///To get letters/alphabets
var letters = new String(item.Where(Char.IsLetter).ToArray());
///to get special characters
var letters = new String(item.Where(Char.IsSymbol).ToArray())
}
Now you can easily combine the codes :)

Convert string[] to Int[] without losing leading zeros

Input:
string param = "1100,1110,0110,0001";
Output:
int[] matrix = new[]
{
1,1,0,0,
1,1,1,0,
0,1,1,0,
0,0,0,1
};
What I did?
First of all I splited string to string[].
string[] resultantArray = param.Split(',');
Created one method, where I passed my string[].
var intArray = toIntArray(resultantArray);
static private int[] toIntArray(string[] strArray)
{
int[] intArray = new int[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
intArray[i] = int.Parse(strArray[i]);
}
return intArray;
}
Issue?
I tried many solutions of SO, but none of them helped me.
Ended up with array without leading zeroes.
determine all digits: .Where(char.IsDigit)
convert the selected char-digits into integer: .Select(x => x-'0') (this is not as pretty as int.Parse or Convert.ToInt32 but it's super fast)
Code:
string param = "1100,1110,0110,0001";
int[] result = param.Where(char.IsDigit).Select(x => x-'0').ToArray();
As CodesInChaos commented, this could lead to an error if there are other type of Digits within your input like e.g. Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙' where char.IsDigit == true - if you need to handle such special cases you can allow only 0 and 1 in your result .Where("01".Contains)
You could also remove the commas and convert the result character-wise as follows using Linq.
string param = "1100,1110,0110,0001";
int[] result = param.Replace(",", "").Select(c => (int)Char.GetNumericValue(c)).ToArray();
yet another way to do this
static private IEnumerable<int> toIntArray(string[] strArray)
{
foreach (string str in strArray)
{
foreach (char c in str)
{
yield return (int)char.GetNumericValue(c);
}
}
}
What about this?
string input = "1100,1110,0110,0001";
var result = input
.Split(',')
.Select(e => e.ToCharArray()
.Select(f => int.Parse(f.ToString())).ToArray())
.ToArray();
string[] s=param.split(',');
Char[] c;
foreach(string i in s){
c+=i.ToCharArray()
}
int[] myintarray;
int j=0;
foreach(char i in c){
myintarray[j]=(int)i;
j++
}

Number extraction from strings using Regex

i have this C# code that i found and then improved upon for my needs, but now i would like to make it work for all numeric data types.
public static int[] intRemover (string input)
{
string[] inputArray = Regex.Split (input, #"\D+");
int n = 0;
foreach (string inputN in inputArray) {
if (!string.IsNullOrEmpty (inputN)) {
n++;
}
}
int[] intarray = new int[n];
n = 0;
foreach (string inputN in inputArray) {
if (!string.IsNullOrEmpty (inputN)) {
intarray [n] = int.Parse (inputN);
n++;
}
}
return intarray;
}
This works well for trying to extract whole number integers out of strings but the issue that i have is that the regex expression i am using is not setup to account for numbers that are negative or numbers that contain a decimal point in them. My goal in the end like i said is to make a method out of this that works upon all numeric data types. Can anyone help me out please?
You can match it instead of splitting it
public static decimal[] intRemover (string input)
{
return Regex.Matches(input,#"[+-]?\d+(\.\d+)?")//this returns all the matches in input
.Cast<Match>()//this casts from MatchCollection to IEnumerable<Match>
.Select(x=>decimal.Parse(x.Value))//this parses each of the matched string to decimal
.ToArray();//this converts IEnumerable<decimal> to an Array of decimal
}
[+-]? matches + or - 0 or 1 time
\d+ matches 1 to many digits
(\.\d+)? matches a (decimal followed by 1 to many digits) 0 to 1 time
Simplified form of the above code
public static decimal[] intRemover (string input)
{
int n=0;
MatchCollection matches=Regex.Matches(input,#"[+-]?\d+(\.\d+)?");
decimal[] decimalarray = new decimal[matches.Count];
foreach (Match m in matches)
{
decimalarray[n] = decimal.Parse (m.Value);
n++;
}
return decimalarray;
}
try modifying you regular expression like this:
#"[+-]?\d+(?:\.\d*)?"

How can I list all latin (English alphabet) characters?

I am looking for an efficient way of getting a list with all English (latin) characters.
A, B, C, .... , Z
I really don't want a constructor like this:
// nasty way to create list of English alphabet
List<string> list = new List<string>();
list.Add("A");
list.Add("B");
....
list.Add("Z");
// use the list
...
If you are curius on how is this usable, I am creating a bin-tree mechanism.
You can do this with a for loop:
List<char> list = new List<char>();
for (char c = 'A'; c <= 'Z'; ++c) {
list.Add(c);
}
If you want a List<string> instead of a List<char> use list.Add(c.ToString()); instead.
Note that this works only because the letters A - Z occur in a consecutive sequence in Unicode (code points 65 to 90). The same approach does not necessarily work for other alphabets.
Here:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
This string is a list of characters.
Use either ToCharArray or the LINQ ToList to convert to an enumerable of your choice, though you can already access each item through the Chars indexer of the string.
Using LINQ
int charactersCount = 'Z' - 'A' + 1;
IList<char> all = Enumerable.Range('A', charactersCount)
.Union(Enumerable.Range('a', charactersCount))
.Select(i => (char)i)
.ToList();
There's no built in way to get a list of strings that correspond to each character. You can get an IEnumerable with the following code, which will probably suit your purposes. You could also just stick with the array in the from section.
var letters = from letter in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
select letter.ToString();
Here is my solution (eventually)
const string driveLetters = "DEFGHIJKLMNOPQRSTUVWXYZ";
List<string> allDrives = new List<string>(driveLetters.Length);
allDrives = (from letter
in driveLetters.ToCharArray()
select letter).ToList();
I ended up with this solution because initially my goal was to create a list of all available drives in windows. This is the actual code:
const string driveLetters = "DEFGHIJKLMNOPQRSTUVWXYZ";
const string driveNameTrails = #":\";
List<string> allDrives = (from letter
in driveLetters.ToCharArray()
select letter + driveNameTrails).ToList();
return allDrives;
The simplest way -
int start = (int) 'A';
int end = (int) 'Z';
List<char> letters = new List<char>();
for (int i = start; i <= end; i++)
{
letters.Add((char)i);
}
Same way but less code -
IEnumerable<char> linqLetters = Enumerable.Range(start, end - start + 1).Select(t => (char)t);
Generate string and convert to array
string str = "abcdefghijklmnopqrstuvwxyz"; //create characters
char[] arr; //create array
arr = str.ToCharArray(0, 26); //You can change the number to adjust this list
Get the value in the array
char getchar = arr[17];//get "r"

Categories

Resources