This question already has answers here:
Is there an equivalent to 'sscanf()' in .NET?
(8 answers)
Closed 6 years ago.
I have a question. I work on a console application and I would like Read 3 variable on the same line.
With the language C we can write this
int a;
string b;
int c;
scanf("%d %s %d", &a, &b, &c);
When I start the program I write : 1+1 on the same line and a = 1 b = "+" c = 1
How can I make the same in C# with console.readline() ?
Thank you in advance,
Nico
This answer is modified from reading two integers in one line using C#. So you can do it several ways as described in this answer, but i would suggest like:
//Read line, and split it by whitespace into an array of strings
string[] scanf= Console.ReadLine().Split();
//Parse element 0
int a = int.Parse(scanf[0]);
//Parse element 1
string b = scanf[1];
//Parse element 2
int c = int.Parse(scanf[2]);
I would suggest following the link as there is more ways described.
No, there is no equivalent, but you can easily create one:
void Scanf(out string[] values)
{
values = Console.ReadLine().Split();
}
However you have to parse every argument in your calling code:
int a;
string b;
int c;
string[] r;
scanf(out r);
int.TryParse(r[0], out a);
b = r[1];
int.TryParse(r[2], out c);
If you want to verify the format of the strings and numbers also you probably need a regex:
var r = new Regex("(\\d+) (\\S+) (\\d+)");
var values = r.Matches(Console.ReadLine())[0];
Now again you need to parse:
int.TryParse(values.Groups[1], out a);
b = values.Groups[2];
int.TryParse(values.Groups[3], out c);
Remember that the first group within a regex allways contains the complete match-string, so the first capturing group has index one.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want an solution to convert an input int say 010 to list of int {0,1,0}.
Below is code I tried, works until 0 is encountered.
Int num = 010;
List<int> listOfInt = new List<int>();
While(num > 0)
listOfInt.Add(num%10);
num / = 10;
I just want to split entered int and convert it to list of int. LINQ is fine if that could be efficient!
As others already mentioned 010 is identical to 10 when having parsed as int. However you could have your number as string coming from a console-input for example.
string myNumber = "010";
This can be split on every character quite easy using LINQ:
var intList = myNumber.Select(x => Convert.ToInt32(x.ToString())).ToList();
As every character is internally an int where '0' equals 49 you have to convert every single character to a string before which is done by using ToString.
Console.WriteLine("Enter a number:")
var input = Console.ReadLine();
List<int> result = input.Select(c => int.Parse(c.ToString())).ToList();
There is no difference between 010 and 10 either in computer arithmetic or real life. Zero is zero.
If you want to convert the number to a specific string format and extract the characters, perform the same steps as the statement:
10.ToString("000").Select(c=>c-48).ToList();
The result is a list with the numbers 0,1,0.
The expression c-48 takes advantage of the fact that characters are essentially ints, and digits start from 0 upwards. So 48 is 0, 1 is 49 etc.
If the input is a string, eg "10" you'll have to pad it with 0s up to the desired length:
"10".PadLeft(3,'0').Select(c=>c-48).ToList()
The result will be 0,1,0 again.
If, after all, you only want to retrieve characters from a paddes string, you only need padding, as a String is an IEnumerable. You can copy the characters to an array with String.ToCharArray() or to a List as before:
"10".PadLeft(3,'0').ToList()
string num = "010";
List<int> listOfInt = new List<int>();
foreach(char item in num)
{
listOfInt.Add(Convert.ToInt32(item.ToString()));
}
This question already has answers here:
Using Linq to get the last N elements of a collection?
(20 answers)
how to take all array elements except last element in C#
(6 answers)
Closed 8 years ago.
I have a string array in c#.Now as per my requirement i have to get the last ,second last and one element before second last elements in string but i am not getting how to get it.
Here is my string array.With Last() i am able to get the last element but second last and before second last i am not getting to find out.
string[] arrstr = str.Split(' ');
With .Last() i am able to get the last element but rest of the elements i am not able to get.
Please help me..
Use:
string[] arrstr = str.Reverse().Take(3).Reverse().ToArray();
In more recent versions of c# you can now use:
string[] arrstr = str.TakeLast(3).ToArray();
var threeLastElments = arrstr.Reverse().Take(3).Reverse().ToArray();
It actually gets the number of elements and skip the remaining element from the total count and take the specified amount
you can replace the 3 with N and use as method
string[] res = arrstr.Skip(Math.Max(0, arrstr.Count() - 3)).Take(3).ToArray();
Get a substring:string arrstr = str.Substring(str.Length - 4, 3);
More on C# strings
Why don't you calculate the length using obj.length; and then use arr[i] inside the loop and start the loop from last value.
To offer another solution, one which will be much more performant than LINQ queries ...
public static string[] getLast3(string[] src)
{
if (src.Length <= 3)
return src;
var res = new string[3];
Array.Copy(src, src.Length - 3, res, 0, 3);
return res;
}
This question already has answers here:
Splitting a string / number every Nth Character / Number?
(17 answers)
Closed 8 years ago.
I have a string that looks something like:
0122031203
I want to be able to parse it and add the following into a list:
01
22
03
12
03
So, I need to get each 2 characters and extract them.
I tried this:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i=i+2) {
mList.Add(_CAUSE.Substring(i, _CAUSE.Length));
}
return mList;
but something is not right here, I keep getting the following:
Index and length must refer to a location within the string. Parameter
name: length
Did I get this wrong?
How about using Linq?
string s = "0122031203";
int i = 0;
var mList = s.GroupBy(_ => i++ / 2).Select(g => String.Join("", g)).ToList();
I believe you have may have specified the length incorrectly in the Substring function.
Try the following:
List<string> mList = new List<string>();
for (int i = 0; i < _CAUSE.Length; i = i + 2)
{
mList.Add(_CAUSE.Substring(i, 2));
}
return mList;
The length should be 2 if you wish to split this into chunks of 2 characters each.
when you do the substring, try _CAUSE.SubString(i, 2).
2points:
1) as previously mentioned, it should be substring(i,2);
2) U should consider the case when the length of ur string is odd. For example 01234: do u want it 01 23 and u'll discard the 4 or do u want it to be 01 23 4 ??
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating an array of letters in the alphabet in C#
(Theoretical question only, was just pondering it as a writing a filtering system (not using an alphabet, but got me thinking)).
So lets say I want to create a filter list of all the capital letters (A-Z) in the English alphabet plus the word "All"
All A B C D E ... X Y Z
And convert it to a List<string> what is the most efficient way to do this in C# Without using the hard coded {"A","B"} method.
Not a duplicate of This question
The question listed above deals with conversion to a plain and simple character array, which wouldn't allow for the ALL portion. And to take that and convert I believe would involve at least a copy + cast.
For 'most efficient' you would try to avoid List<> and LINQ.
var sb = new StringBuilder("All", 26+3 +spare);
for (char c = 'A'; c <= 'Z'; c++) sb.Append(c);
string result = sb.ToString();
but to be honest you would have to benchmark the various answers here.
You can also do it with actual characters:
List<string> characters = new List<string>();
for (char c = 'A'; c <= 'Z'; c++)
characters.Add("" + c);
Each string character is a char value that has a number an ascii. Capital A starts at 65 and Captial Z is 90. Thus using a loop you can generate the values.
List<string> alpha = new List<string>();
for(int i=65; i <=90; i++) {
alpha.add(""+(char)i);
}
EDIT:
You could also use the character literals for the for loop as
for(int i = (int)'A'; i <= (int)'Z'; i++)
For example:
var alphabet = new List<String>(27);
var capitalRange = Enumerable.Range(0, 26)
.Select(i => new String(Convert.ToChar(i + 65), 1));
alphabet.AddRange( capitalRange );
alphabet.Add("All");
Note that the initialization of the list with the correct capacity ensures that it doesn't need to be resized and won't be oversized. Apart from that this is similar to a for-loop.
The string constuctor is slightly faster than a Char.ToString().
Here is a fairly compact way to do it:
var list = new[] { "All" }.Concat(
Enumerable.Range('A', 'Z' - 'A' + 1)
.Select(c => ((char)c).ToString())
).ToList();
But something like this is cleaner (IMO) and more efficient since there is no resizing:
const char start_ch = 'A';
const char end_ch = 'Z';
var list = new List<string>(end_ch - start_ch + 1) { "All" };
for (char ch = start_ch; ch <= end_ch; ++ch)
list.Add(ch.ToString());
What exactly do you intend to do with this List? For example, searching can be more efficiently done using an associative data structure instead, such as HashSet or Dictionary.
This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 7 years ago.
Say I have 12345.
I'd like individual items for each number. A String would do or even an individual number.
Does the .Split method have an overload for this?
I'd use modulus and a loop.
int[] GetIntArray(int num)
{
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
listOfInts.Reverse();
return listOfInts.ToArray();
}
Something like this will work, using Linq:
string result = "12345"
var intList = result.Select(digit => int.Parse(digit.ToString()));
This will give you an IEnumerable list of ints.
If you want an IEnumerable of strings:
var intList = result.Select(digit => digit.ToString());
or if you want a List of strings:
var intList = result.ToList();
Well, a string is an IEnumerable and also implements an indexer, so you can iterate through it or reference each character in the string by index.
The fastest way to get what you want is probably the ToCharArray() method of a String:
var myString = "12345";
var charArray = myString.ToCharArray(); //{'1','2','3','4','5'}
You can then convert each Char to a string, or parse them into bytes or integers. Here's a Linq-y way to do that:
byte[] byteArray = myString.ToCharArray().Select(c=>byte.Parse(c.ToString())).ToArray();
A little more performant if you're using ASCII/Unicode strings:
byte[] byteArray = myString.ToCharArray().Select(c=>(byte)c - 30).ToArray();
That code will only work if you're SURE that each element is a number; otherisw the parsing will throw an exception. A simple Regex that will verify this is true is "^\d+$" (matches a full string consisting of one or more digit characters), used in the Regex.IsMatch() static method.
You can simply do:
"123456".Select(q => new string(q,1)).ToArray();
to have an enumerable of integers, as per comment request, you can:
"123456".Select(q => int.Parse(new string(q,1))).ToArray();
It is a little weak since it assumes the string actually contains numbers.
Here is some code that might help you out. Strings can be treated as an array of characters
string numbers = "12345";
int[] intArray = new int[numbers.Length];
for (int i=0; i < numbers.Length; i++)
{
intArray[i] = int.Parse(numbers[i]);
}
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5