Why i can't convert this string to a number? Or how to make a array of numbers from this string.
string str = "110101010";
int c = Int32.Parse(str[0]);
str is a string so str[0] returns a char and the Parse method doesnt take a char as input but rather a string.
if you want to convert the string into an int then you would need to do:
int c = Int32.Parse(str); // or Int32.Parse(str[0].ToString()); for a single digit
or you're probably looking for a way to convert all the individual numbers into an array which can be done as:
var result = str.Select(x => int.Parse(x.ToString()))
.ToArray();
I assume you are trying to convert a binary string into its decimal representation.
For this you could make use of System.Convert:
int c = Convert.ToInt32(str, 2);
For the case that you want to sum up all the 1s and 0s from the string you could make use of System.Linq's Select() and Sum():
int c = str.Select(i => int.Parse(i.ToString())).Sum();
Alternatively if you just want to have an array of 1s and 0s from the string you could omit the Sum() and instead enumerate to an array using ToArray():
int[] c = str.Select(i => int.Parse(i.ToString())).ToArray();
Disclaimer: The two snippets above using int.Parse()would throw an exception if str were to contain a non-numeric character.
Int32.Parse accepts string argument, not char which str[0] returs.
To get the first number, try:
string str = "110101010";
int c = Int32.Parse(str.Substring(0, 1));
Related
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 want to convert the following string to an array of an integral number type.
string str = "-9007199254740985";
I tried str.ToArray().ToString(); but did not get the right conversion.
Below code will convert the string to character array.
string input = "welcome";
char[] chars = input.ToCharArray();
If you want to convert the string to an array, you can do it like this.
var array = new string[] { str };
However, if you want an array of long, you have to convert your string first.
var number = long.Parse(str);
Then you can add it to an array.
var array = new long[] { number };
Note that you cannot use an int here, because your number exceeds its range.
I need to extract a string into 3 different variables.
The input from the user will be in this format 13,G,true.
I want to store the number in an integer, the "G" in a character and "true" into a string.
But I don't know how to specify the comma location so the characters before or after the comma can be stored in another variable.
I'm not allowed to use the LastIndexOf method.
string msg = "13,G,true";
var myArray = msg.Split(",");
// parse the elements
int number;
if (!Int32.TryParse(myArray[0], out number) throw new ArgumentException("Whrong input format for number");
string letter = myArray[1];
string b = myArry[2];
// or also with a boolean instead
bool b;
if (!Int32.TryParse(myArray[2], out b) throw new ArgumentException("Whrong input format for boolean");
use String.Split
string str='13,G,true';
string[] strArr=str.Split(',');
int32 n=0,intres=0;
char[] charres = new char[1];
string strres="";
if(!Int32.TryParse(strArr[0], out n))
{
intres=n;
}
if(strArr[0].length>0)
{
charres[0]=(strArr[1].toString())[0];
}
strres=strArr[2];
//you'll get 13 in strArr[0]
//you'll get Gin strArr[1]
//you'll get true in strArr[2]
var tokens = str.Split(","); //Splits to string[] by comma
var first = int32.Parse(tokens[0]); //Converts first string to int
var second = tokens[1][0]; //Gets first char of the second string
var third = tokens[2];
But be aware, that you also need to validate the input
You are going to need method String.Split('char'). This method splits string using specified char.
string str = "13,G,true";
var arrayOfStrings=str.Split(',');
int number = int.Parse(arrayOfStrings[0]);
// original input
string line = "13,G,true";
// splitting the string based on a character. this gives us
// ["13", "G", "true"]
string[] split = line.Split(',');
// now we parse them based on their type
int a = int.Parse(split[0]);
char b = split[1][0];
string c = split[2];
If what you are parsing is CSV data, I would check out CSV parsing libraries related to your language. For C#, Nuget.org has a few good ones.
I am adding a new record to XML file, first I'm querying all existing items and storing the count in an int
int number = query.count()
and then increment the number by 1.
number = number + 1;
Now I want to format this value in a string having N00000000 format
and the number will occupy the last positions.
Pseudo code:
//declare the format string
sting format = "N00000000"
//calculate the length of number string
int length =number.ToString().Length();
// delete as many characters from right to left as the length of number string
???
// finally concatenate both strings with + operator
???
String output = "N" + String.Format ("00000000", length)
Alternatively if you change your formatstring to "'N'00000000" you can even use:
String output = String.Format (formatString, length)
Which means you can fully specify your output by changing your formatstring without having to change any code.
int i = 123;
string n = "N" + i.ToString().PadLeft(8, '0');
var result = number.ToString("N{0:0000000}");
HTH
You can use the built in ToString overload that takes a custom numeric format string:
string result = "N" + number.ToString("00000000");
Here is a another one ...
result = String.Format("N{0:00000000}",number);
Suppose I have a string "011100011".
Now I need to find another string by adding the adjacent digits of this string, like the output string should be "123210122".
How do I split each characters in the string and manipulate them?
The method that I thought was to convert the string to integer using Parsing and splitting each character using modulus or something and performing operations on them.
But can you suggest some simpler methods?
Here's a solution which uses some LINQ plus dahlbyk's idea:
string input = "011100011";
// add a 0 at the start and end to make the loop simpler
input = "0" + input + "0";
var integers = (from c in input.ToCharArray() select (int)(c-'0'));
string output = "";
for (int i = 0; i < input.Length-2; i++)
{
output += integers.Skip(i).Take(3).Sum();
}
// output is now "123210122"
Please note:
the code is not optimized. E.g. you might want to use a StringBuilder in the for loop.
What should happen if you have a '9' in the input string -> this might result in two digits in the output string.
Try converting the string to a character array and then subtract '0' from the char values to retrieve an integer value.
string input = "011100011";
int current;
for (int i = 0; i < input.Length; i ++)
{
current = int.Parse(input[i]);
// do something with current...
}