I want to declare string dynamically for example
int i =2;
then declare two string
string str1 ="";
string str2 ="";
So basically I want to declare string based on i.
You need an array, you can't do it like that:
int i = 2; // get the input from somewhere
var values = new string[i];
But that doesn't mean it's not possible.You can even create dynamic assemblies,classes,properties,if you really want to.See this documentation for more details: Emitting Dynamic Methods and Assemblies
Use Lists like this...
List<string> MyStrings = new List<string>();
Console.Write("Enter the number of strings you want to create > :: ");
int n = int.Parse(Console.ReadLine());
for (int i = 0; i < n; i++)
{
MyStrings.Add("String"+i.ToString());
}
foreach (var str in MyStrings)
{
Console.WriteLine(str);
}
Related
I'm struggling to find a way to first
Get User input to decide how many elements will be in the next string array
Then to convert the Users input from string to int for the array
Is there also a way to display the element number along with the string element like so.... Console.WriteLine(1. StringName 2.StringName);
This is my code :
Console.WriteLine("How many countries you want mate ? ");
string numberOfCountries = Console.ReadLine();
Console.WriteLine("Please name your countries ");
string[] nameOfCountries = new string[10];
for (int i = 0; i < nameOfCountries.Length ; i++)
{
nameOfCountries[i] = Console.ReadLine();
}
Get User input to decide how many elements will be in the next string array
You can put a variable in when creating an array size, like this:
string[] nameOfCountries = new string[someVariable];
someVariable needs to be an int. Console.WriteLine returns a string, so you need to parse the string to an int. You can use int.Parse for that. So:
int numberOfCountries = int.Parse(Console.ReadLine());
string[] nameOfCountries = new string[numberOfCountries];
Note that Parse will throw an exception if it isn't able to correctly parse the input in to an integer.
Is there also a way to display the element number along with the string element
You can use a similar loop like you are when you are assigning values to the array.
Console.WriteLine("{0}: {1}", i, nameOfCountries[i]);
Program:
string mate = "mate";
Console.WriteLine($"How many countries you want {mate}?");
string numberOfCountries = Console.ReadLine();
int numberOfCountriesInt;
while ( !int.TryParse( numberOfCountries, out numberOfCountriesInt ) )
{
mate = mate.Insert(1, "a");
Console.WriteLine($"How many countries you want {mate}?");
numberOfCountries = Console.ReadLine();
}
Console.WriteLine("Please name your countries ");
string[] namesOfCountries = new string[numberOfCountriesInt];
for (int i = 0; i < namesOfCountries.Length; i++)
{
namesOfCountries[i] = Console.ReadLine();
}
for (int i = 0; i < namesOfCountries.Length; i++)
{
Console.WriteLine($"{i+1}, {namesOfCountries[i]}");
}
Output:
How many countries you want mate?
Two
How many countries you want maate?
Two?
How many countries you want maaate?
2
Please name your countries
Stralya
PNG
1. Stralya
2. PNG
Please note that a List<string> may be better to store data like this. Then you can do something like this:
Console.WriteLine("Please name your countries ");
var namesOfCountries = new List<string>();
for (int i = 0; i < numberOfCountriesInt; i++)
{
namesOfCountries.Add(Console.ReadLine());
}
I need to set a new string and that the user need to set this new string name
for example:
int input = 0;
while (input != -1)
{
input = int.Parse(Console.ReadLine());
int count = 0;
count ++;
int ("the " count)= intput;
}
You don't want a "dynamic variable", you want a dictionary. Something like this:
Dictionary<int, int> values = new Dictionary<int, int>();
int count = 0;
int input = 0;
while (input != -1)
{
input = int.Parse(Console.ReadLine());
count++;
values.Add(count, input);
}
You can do your "the" part in some output if you need to, but the values being stored in this case appear to be just int values anyway. If you want to get creative you can wrap some data types in a custom class and output formatted strings from that class easily enough.
Another change to note above is moving the declaration of count outside of the loop, otherwise it's always going to be 1.
Basically, just about any time you find yourself wanting a dynamic variable name following some pattern, what you actually want is a collection of some kind. Maybe a dictionary, maybe a list, maybe something else, etc.
I think, that is, waht do ypu need:
int input = 0;
var inputs = new List<int>();
while (input != -1)
{
input = int.Parse(Console.ReadLine());
int count = 0;
count++;
inputs.Add(input);
}
var result = inputs.Select((j, i) => Tuple.Create("The " + i, j)).ToList();
My front-end application sends strings that look like this:
"12-15"
to a back-end C# application.
Can someone give me some pointers as to how I could extract the two numbers into two variables. Note the format is always the same with two numbers and a hyphen between them.
string stringToSplit = "12-15";
string[] splitStringArray;
splitStringArray = stringToSplit.Split('-');
splitStringArray[0] will be 12
splitStringArray[1] will be 15
Split the string into parts:
string s = "12-15";
string[] num = s.Split('-');
int part1 = Convert.ToInt32(num[0]);
int part2 = Convert.ToInt32(num[1]);
int[] numbers = "12-15".Split('-')
.Select(x => {
int n;
int.TryParse(x, out n);
return n;
})
.ToArray();
We call Split on a string instance. This program splits on a single character
string s ="12-15";
string[] words = s.Split('-');
foreach (string word in words)
{
int convertedvalue = Convert.ToInt32(word );
Console.WriteLine(word);
}
string[] ss= s.Split('-');
int x = Convert.ToInt32(ss[0]);
int y = Convert.ToInt32(ss[1]);
more info
You can use the below code to split and it will return string for each value, then you can typecast it to any type you wish to ...
string myString = "12-15-18-20-25-60";
string[] splittedStrings = myString.Split('-');
foreach (var splittedString in splittedStrings)
{
Console.WriteLine(splittedString + "\n");
}
Console.ReadLine();
Here is the correct version without the wrong code
string textReceived = "12-15";
string[] numbers = textReceived.Split('-');
List<int> numberCollection = new List<int>();
foreach (var item in numbers)
{
numberCollection.Add(Convert.ToInt32(item));
}
String numberString = "12-15" ;
string[] arr = numberString.Split("-");
Now you will get a string array , you can use parsing to get the numbers alone
int firstNumber = Convert.ToInt32(arr[0]);
Helpful answer related to parsing :
https://stackoverflow.com/a/199484/5395773
You could convert that string explicitly to an integer array using Array.ConvertAll method and access the numbers using their index, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = Array.ConvertAll(number.Split('-'), int.Parse);
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[1]);
}
}
}
Or you can explicitly convert the numeric string using int.Parse method, the int keyword is an alias name for System.Int32 and it is preffered over the complete system type name System.Int32, you can run the below example here.
using System;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
var number = "12-15";
var numbers = number.Split('-');
var one = int.Parse(numbers[0]);
var two = int.Parse(numbers[1]);
Console.WriteLine(one);
Console.WriteLine(two);
}
}
}
Additional read: Please check int.Parse vs. Convert.Int32 vs. int.TryParse for more insight on parsing the input to integer
string str = null;
string[] strArr = null;
int count = 0;
str = "12-15";
char[] splitchar = { '-' };
strArr = str.Split(splitchar);
for (count = 0; count <= strArr.Length - 1; count++)
{
MessageBox.Show(strArr[count]);
}
Good day. I would like to ask if it is possible to concatenate 2 strings to get another variable.
Lets say I have this code:
string num1 = "abcdefgh";
string num2 = "ijklmnop";
int numLength = 0;
And I want to get the value of both num1 and num2 using a forloop
for(int i =1; i<= 2; i++)
{
numLength = ("num" + i).Length + numLength;
}
Console.WriteLine("Length is {0}", numLength);
I want it to output
Length is 16
I did the above code but it actually gives me different value.
Edit1: (P.S. I will be using more than 10 variables, I just indicated 2 of it to make it simple)
Edit2: Yes, yes. I want ("num"+i).Length to give me num1.Legnth + num2.Length.
First way:
I suggest you to add all of your strings into the List and then get the total length with Sum method.
List<string> allStrings = new List<string>();
allStrings.Add(num1);
allStrings.Add(num2);
...
allStrings.Add(num10);
var totalLength = allStrings.Sum(x => x.Length);
Second way
Or if you want to calculate total length with for loop:
int totalLength = 0;
for (int i = 0; i < allStrings.Count; i++)
{
totalLength = totalLength + allStrings[i].Length;
}
Third way
If you don't want to use List, then you can use String.Concat and then Length property.
var totalLength = String.Concat(num1, num2).Length;
The result is 16 in your case.
Edit:
In my opinion you think that, ("num" + i).Length will give you num1.Length and num2.Length. This is wrong.
Lets say we have some strings and we want the total length for all this strings.
In this case you need to store all strings in an array, so you can counter them and use indexes.
and after that a simple for (or foreach) loop can solve the problem:
string[] texts = new string[20]; //You can use any number u need, but in my code I wrote 20.
texts[0] = "sample text 1";
texts[1] = "sample text 2";
// add your strings ...
int totalLenght = 0;
foreach (string t in texts)
{
totalLenght += t.Length;
}
Console.WriteLine("Length is {0}", totalLenght);
If you need a variable with unlimited size, use List<T>
here is example:
List<string> texts = new List<string>();
texts.Add("sample text 1");
texts.Add("sample text 2");
// add your strings ....
int totalLenght = 0;
for (int i = 0; i < texts.Count; i++)
{
totalLenght += texts[i].Length;
}
Console.WriteLine("Length is {0}", totalLenght);
When I print my List (inventory) it prints the same values multiple times instead of iterating properly:
List<Coffee> inventory = new List<Coffee>();
Console.Write("Enter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast ");
string s = Console.ReadLine();
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
// Loop
while (!s.ToLower().Equals("q"))
{
string name = values[0];
string demand = (values[1]);
string cost = (values[2]);
string min = values[3];
float D = CheckDemand(demand);
float C = CheckCost(cost);
float M = CheckMin(min);
Decaf decafCoffee = new Decaf(name, D, C, M);
inventory.Add(decafCoffee);
Console.Write("\nEnter q to quit or the whole data as a comma delimited string using the following format Name,D,C,D:minQ or R:roast: ");
s = Console.ReadLine();
} // End loop
// Display values
Console.WriteLine("\nName \t C ($) Demand \t Detail Q(lbs.) TAC ($) T(weeks) ");
for (int j = 0; j < inventory.Count; j++)
{
Console.WriteLine("{0}", inventory[j].toString());
}
Any ideas why this is? Do I need to implement a certain interface?
Move your line with string[] values inside the while-loop:
string s = Console.ReadLine();
// Loop
while (!s.ToLower().Equals("q"))
{
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
...
When you call ToString() on an object you will typically just get the fully qualified name of the type. It depends what you want to see printed, but you should try displaying the members of the Coffee class. For example:
foreach(Coffee c in inventory)
{
Console.WriteLine(c.Name);
}
I went ahead and switch you from a for loop to a foreach.
You need to put
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
inside your while loop.