String name of a other string name - c#

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();

Related

How do you get user input to decide how many elements are in a string array?

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());
}

Input string was not in a correct format, List<String> to Dictionary<int, int>

I am trying to create a program that reads user inputted integers from the console, then creates a Dictionary<int, int>, and finally prints all inputs with the number of times they have been entered.
My idea was to collect each entry until an empty line in a List. Then I would parse it and create the dictionary with input for Key and times typed as Value.
I get "Unhandled Exception: System.FormatException: Input string was not in a correct format" at int integer = int.Parse(number); and nothing gets printed.
Would you please help me understand where the code falls apart. I am a beginner and not sure how to correct it.
static void Main(string[] args)
{
string input = "0";
List<string> listNumbers = new List<string>();
Console.WriteLine("Type several numbers and press Enter after each one:");
while (input != string.Empty)
{
input = Console.ReadLine();
listNumbers.Add(input);
}
IDictionary<int, int> intOccurences = new Dictionary<int, int>();
foreach (string number in listNumbers)
{
int integer = int.Parse(number);
int count;
if (!intOccurences.TryGetValue(integer, out count))
{
count = 0;
}
intOccurences[integer] = count + 1;
}
PrintNumbers(intOccurences);
}
private static void PrintNumbers(IDictionary<int, int> intOccurences)
{
foreach (KeyValuePair<int, int> entry in intOccurences)
{
Console.WriteLine(
"Number '{0}' occurs {1} time (s) in the input.", entry.Key, entry.Value);
}
}
Consider using TryParse:
string possibleInteger ="12";
int resultInteger;
bool isCorrectInteger = int.TryParse(possibleInteger, out resultInteger);
if (isCorrectInteger)
{
// add to dictionary
}
else
{
Console.WriteLine("Not a correct integer number");
}
Also, remember to consider your Culture settings while parsing numbers and dates. For example if the current language uses/doesn't use some decimal separator or thausand separator, you may end up with format exceptions. If it is a factor in your case, consider using the version of TryParse that takes it into account.
Possible solution
Replace
int integer = int.Parse(number);
With
int integer;
var isInteger = int.TryParse(number, out integer);
if(!isInteger) continue; // Not a number skip
if (!intOccurences.TryGetValue(integer, out count))
{
count = 0;
}
Idea remains, skip the non integers, else devise a mechanism to handle them. You cannot int.parse(<Non Integer>)
You could try directly converting to integers immediately after reading a line from the console, adding them to a list of integers. This makes everything easier to understand as well. For example:
IDictionary<int, int> intOccurences = new Dictionary<int, int>();
List<int> allInputs = new List<int>();
while (input != string.Empty)
{
input = Console.ReadLine();
allInputs.Add(Convert.ToInt32(input));
}
foreach (int i in allInputs)
{
int currentCount; //defaults to 0
intOccurences.TryGetValue(i, out currentCount);
frequencies[i] = currentCount + 1;
}

c# string concat to get another variable

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);

Dynamically declare string variables

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);
}

Trying to get the largest int in each line of a file and sum the result

When I try and run my code I get the error:
Input string was not in a correct format.
I am trying to find the largest int in each line of a text file and then add them all up.
I am sure that there are no letters in this file and everything is separated by a space.
Here is my code:
int counter = 0;
string line;
List<int> col = new List<int>();
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(label3.Text);
while ((line = file.ReadLine()) != null)
{
int[] storage = new int[10000];
Console.WriteLine(line);
counter++;
string s = line;
string[] words = s.Split(' ');
for (int i = 0; i < words.Length; i++)
{
storage[i] = Convert.ToInt32(words[i]);
}
int large = storage.Max();
col.Add(large);
Console.WriteLine(" ");
foreach (int iii in col)
{
Console.WriteLine(iii);
}
int total = col.Sum();
Console.WriteLine(total);
}
file.Close();
// Suspend the screen.
Console.ReadLine();
It's possible that target string cannot be stored in a 32 bit integer. You can try parsing to ulong type. Take a look at Integral Types Table and Floating-Point Types Table.
Instead of doing Convert.ToInt32(), try int.TryParse(). It will return a bool value telling you if operation succeeded, and it has an out parameter where it will place result of parse operation. TryParse operation is also available on other numeric types if you decide you need them.
E.g.
int val;
string strVal = "1000";
if (int.TryParse(strVal, out val))
{
// do something with val
}
else
{
// report error or skip
}
I did a quick test and it is likely you get the error in the line
storage[i] = Convert.ToInt32(words[i]);
If so, make sure what you are trying to convert is an integer and not an empty string, for example.
I believe that the line in your code that can cause this error is
Convert.ToInt32(words[i]);
Now, when you're running this application in debug mode(which you probably are) in visual studio, you have a way to check what's going on in your program when the exception happens.
At the very very bottom of your screen is going to be some tabs. these tabs include your error list among other things. The ones I like to use are called "Locals" and "Watch". You can use the Locals tab.
When you click on the Locals tab, you should see a tree structure of all the local variables in your program. if you expand the words variable, you should see all the individual members of the array. you should also be able to see the variable i check the i'th member of your words array, and make sure that it's an integer, and not something else.
You're either converting out of size, or attempting to parse a return carriage '/r'
Make sure you're trimming your input.
My solution:
static void Main(string[] args)
{
int linecount = 100;
string path = #"C:\test\test.txt";
Random rand = new Random();
//Create File
StreamWriter writer = new StreamWriter(path, false);
for (int i = 0; i < linecount; i++)
{
for (int j = 0; j < rand.Next(10, 15); j++)
{
writer.Write(rand.Next() + " ");
}
writer.WriteLine("");
}
writer.Close();
//Sum File
long sum = Enumerable.Sum<string>(
(new StreamReader(path)).ReadToEnd().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries),
l => Enumerable.Max(
l.Split(' '),
i => String.IsNullOrEmpty(i.Trim()) ? 0 : long.Parse(i.Trim())
)
);
}

Categories

Resources