I am taking input from a text box. I've saved the input digits from text box to an array like this:
char[] _array = textBox1.Text.ToCharArray(0, textBox1.Text.Length);
Now I want to convert the array to an int array because I want to perform mathematical operations on each index of the array.
How can I achieve the goal?
Thanks.
You could do it with LINQ if you just want the character code of each char.
var intArrayOfText = "some text I wrote".ToCharArray().Select(x => (int)x);
or
var intArrayOfText = someTextBox.Text.ToCharArray().Select(x => (int)x);
If each character expected to be a digit, you can parse it to an int:
List<int> listOfInt = new List<int>();
_array.ToList().ForEach(v => listOfInt.Add(int.Parse(v.ToString())));
int[] _intArray = listOfInt.ToArray();
Character code value:
List<int> listOfCharValue = new List<int>();
_array.ToList().ForEach(v => listOfCharValue.Add((int)v));
int[] _charValueArray = listOfCharValue.ToArray();
You need to handle exceptions.
Assuming what I asked in my comment is true:
string[] ints = { "1", "2", "3" };
var str = ints.Select(i => int.Parse(i));
However, the above will work only if you have already validated that your input from the text box is numeric.
I've solved my problem. I used list to accomplish the task.
I stored each array index at the relative index of the list after converting each index value to int.
Using list seems more convenient way to me. :)
Thanks to all of you.
Related
I am trying to get an input of #1-1-1 and I need to take the numbers from this string and put them into a list of type int. I have tried to do this using this code:
List<int>numbers = new List<int>();
numbers = Console.ReadLine().Split('-', '#').ToList().ConvertAll<int>(Convert.ToInt32);
Shouldn't the input get split into an array of the numbers I want, then get turned into a list, then get converted into a int list?
Your problem is not the .split('-','#'). This splits the string into a string[] with four entrys (in this example). The first one is an empty string. This cannot be convertet into a Int32.
As a hotfix:
var numbers = Console.ReadLine().Split('-', '#').ToList();
//numbers.RemoveAt(0); <- this is also working
numbers.Remove(string.Empty);
var ret = numbers.ConvertAll<int>(Convert.ToInt32);
That will work for your "#1-1-1 " case. But you should check for non integer chars in the list before converting.
string input = " #1-1-1";
var numbers = Console.ReadLine().Replace("#", "").Split('-').Select(int.Parse).ToList();
You can do it this way
List<int> numbers = new List<int>();
string[] separators = new string[] { "-", "#" };
numbers = Console.ReadLine().Split(separators,StringSplitOptions.RemoveEmptyEntries).ToList().ConvertAll<int>(Convert.ToInt32);
I'm new for C#, but have some basic question:
I need to convert some words, for example: "Hello"(string) to list of letters" "H","e","l","l","o".
Or Number 3242, to list or array of numbers: [3,2,4,2].
How to do that?
And how after that I can change any number or letter in lists?
In Python its very easy. But in C# I don't know what to do.
Please provide LOGICAL and EASY solution. I don't need some 50 lines script which using 20 functions. I'm interested in basic understanding of that process with easy solution, if it existing.
Thank you guys,
P.S: i'm using .Net 3.1
You can use ToCharArray() function to convert input string to character array.
If it is a type other than string then first convert it to String
Copies the characters in this instance to a Unicode character array.
var input = "Hello world";
if(input is string) //Convert word to an array of char
return input.ToCharArray();
if(input is int) //Convert Number to an array of char
return input.ToString() //First convert number to string
.Select(x => int.Parse(x.ToString())) //Iterate over each digit and convert to int.
.ToArray(); //Convert IEnumerable to Array
As Prasad already told you what you have to use, Let me give you some examples about how you going to do it:
For String Type
Lets say there is a string:
string text = ".Net is Awesome";
To store this string as char[]:
char[] CharArray = text.ToCharArray();
To store this string as List<char>:
List<char> CharArray = text.ToCharArray().ToList();
Interestingly, for string Type variable you can directly use .ToList():
List<char> CharArray = text.ToList();
For Int Type
Now lets say you have an int:
int num = 123456;
To store this int as char[]:
char[] numArray = num.ToString().ToCharArray(); //Stored as char array no arithematic operation can be done.
Using Convert.ToInt32()
To store this int as int[]:
int[] numArray = num.ToString().Select(x => Convert.ToInt32(x)).ToArray(); //Arithematic Operations allowed
To store this int as List<int>:
List<int> numArray = num.ToString().Select(x => Convert.ToInt32(x)).ToList(); //Arithematic Operations allowed
Using int.Parse()
To store this int as int[]:
int[] numArray = num.ToString().Select(x => int.Parse(x.ToString())).ToArray(); //Arithematic Operations allowed
To store this int as List<int>:
List<int> numArray = num.ToString().Select(x => int.Parse(x.ToString())).ToList(); //Arithematic Operations allowed
Use below code
var inputStringData = "Hello";//string
var charArray = inputStringData.ToCharArray() ;
var inputNumberData = 3242;//Number
int[] result = inputNumberData.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();
I have an array of strings, and I want to return an array of their lengths. Of course I could do a for loop and iterate, however I'm wondering if there's a more elegant solution, like using Linq, or some other fast/pretty one-liner.
Use the Select function to "transform" each item into another value:
var words = new[] { "some", "words", "go", "here" };
var lengths = words.Select(s => s.Length);
Using the following code:
var stringArray = new string[] {"1","12","123","1234"};
stringArray.AsParallel().ForAll(z => Console.WriteLine(z.Length));
The output should then be:
4
2
3
1
I have a List<string> that will have an item in it like 2014-11-03 23:58:37.6750486_0003 and I was wondering how it could strip the following items from the list:2014-11-03 and .6750486_0003, leaving only 23:58:37.
Using the following to add the item to the List:
calltimeList.Add(msg.timestamp().as_creator_time(header.tz_offset()).ToString());
Using this
Console.WriteLine(entryTime.Substring(11, 8));
Works fine since it will always start # 11 and only be 8 characters
You can use LINQ:
List<string> lst = new List<string> { "2014-11-03 23:58:37.6750486_0003" };
List<string> calltimeList = lst.Select(s => new string(s.SkipWhile(c => c != ' ').Skip(1).TakeWhile(c => c != '.').ToArray())).ToList();
Split the string into two parts, then take the first string and use this in your list.
The Split method will return the split string into an array, so you will have the correct part in the first place in the array.
var stringYouWant = msg.timestamp().as_creator_time(header.tz_offset()).ToString().Split(',')[0];
You could substring the the string value or convert to a DateTime then use and formatter to get the desired value.
string timestamp = "2014-11-03 23:58:37.6750486_0003";
int index=timestamp.IndexOf(":");
timestamp.Substring(index - 2, 8);
or
string timestamp = "2014-11-03 23:58:37.6750486_0003";
int index = timestamp.IndexOf("_");
var time = DateTime.Parse(timestamp.Substring(0, index));
you could so something like
var newList= callTimeList.Select(c=>c.Substring(11,8)).ToList();
but I think a better solution would be to store your callTimeList as a list of dates and then stringify it as needed. My initial though was to convert the string into a date and then format it
var newList = callTimeList.Select(c=> String.Format("{0:HH:mm:ss}",c)).ToList();
but I'm not familiar with the _0003 stuff, but it isn't parsable by DateTime.Parse.
A simple SubString would do.
msg.timestamp().as_creator_time(header.tz_offset()).ToString().SubString(11, 8)
However, looks like you are working with a timestamp. If you can get a hold of the DateTime , it's more readable to do something like
myDateTime.ToString("HH:mm:ss")
I'm stuck. (got a thinking barrier right now) :/
I need a stringarray from a string which contaions a lot of "sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."
There are always 8 values in this string. I want each (of these 8 ) values in the array[8].
But most importantly are the value. (the text at the beginning is unnecessary).
Would this work:
var source = "sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."
var result = source.Split(new []{"\n\t\t\t\t"}, StringSplitOptions.None);
that is: guessing that all your values are separated by that newline+4 tabs.
If that is not (always) the separator, then you need to specify how to identify a "value" from a "separator".
I think the following code will do what you need
int i,j;
int[] array=new int[8];
string s="sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."; // or input something
for(i=j=0;i<s.Length;i++){
if (s[i]>='0'&&s[i]<='9'){
array[j++]=s[i]-'0';
}
}