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.
Related
I have huge string e.g (This is just the part, the string looks same it has just a bit different values).
string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";
So I have to swap the whole number e.g.
Output should be:
9.16364437205161 48.7465504247904
Also I need to swap the first and second part.
So I've tried to split the string, and then to replace the old one with the new one.
string numbers = "48.7465504247904 9.16364437205161 48.7465666577545 9.16367275419435 48.746927738083 9.16430761814855 48.7471066512883 9.16462219521963 48.7471147950429";
string output = "";
double first = 0;
double second = 0;
for (int i = 0; i < numbers.Length; i++)
{
numbers.Split(' ');
first = numbers[0];
second = numbers[1];
}
output = numbers.Replace(numbers[1], numbers[0]);
Console.WriteLine(output);
But my variable first always after the loop has the value 52.
Right now my output is: 44.7465504247904 9.16364437205161, it changed the first part, also it calculates somehow -4
.
You're not assigning anything to the value coming back from .Split and, if I read this right, you're also iterating each character in the numbers array for unclear reasons.
Using .Split is all you need ... well, and System.Linq
using System.Linq;
// ...
string SwapNumbers(string numbers) {
return numbers.Split(' ').Reverse().Join();
}
The above assumes you want to reverse the whole series of numbers. It absolutely does not swap 1,2 then swap 3,4 etc. If that's what you're looking for, it's a bit more involved and I'll add that in a second for funsies.
string SwapAlternateNumbers(string numbersInput) {
var wholeSeries = numbersInput.Split(' ').ToList();
// odd number of inputs
if (wholeSeries.Count % 2 != 0) {
throw new InvalidOperationException("I'm not handling this use case for you.");
}
var result = new StringBuilder();
for(var i = 0; i < wholeSeries.Count - 1; i += 2) {
// append the _second_ number
result.Append(wholeSeries[i+1]).Append(" ");
// append the _first_ number
result.Append(wholeSeries[i]).Append(" ");
}
// assuming you want the whole thing as a string
return result.ToString();
}
Edit: converted back to input and output string. Sorry about the enumerables; that's a difficult habit to break.
here
public static void Main()
{
string nums = "48.7465504247904 9.16364437205161 48.7465504247904 9.16364437205161";
var numbers = nums.Split(' ');
var swapped = numbers.Reverse();
Console.WriteLine("Hello World {"+string.Join(" ",swapped.ToArray())+"}");
}
My program has about 25 entries, most of them string only. However, some of them are supposed to have digits in them, and I don't need those digits in the output (output should be string only). So, how can I "filter out" integers from strings?
Also, if I have integers, strings AND chars, how could I do it (for example, one ListBox entry is E#2, and should be renamed to E# and then printed as output)?
Assuming that your entries are in a List<string>, you can loop through the list and then through each character of each entry, then check if it is a number and remove it. Something like this:
List<string> list = new List<string>{ "abc123", "xxx111", "yyy222" };
for (int i = 0; i < list.Count; i++) {
var no_numbers = "";
foreach (char c in list[i]) {
if (!Char.IsDigit(c))
no_numbers += c;
}
list[i] = no_numbers;
}
This only removes digits as it seems you wanted from your question. If you want to remove all other characters except letters, you can change the logic a bit and use Char.IsLetter() instead of Char.IsDigit().
You can remove all numbers from a strings with this LINQ solution:
string numbers = "Ho5w ar7e y9ou3?";
string noNumbers = new string(numbers.Where(c => !char.IsDigit(c)).ToArray());
noNumbers = "How are you?"
But you can also remove all numbers from a string by using a foreach loop :
string numbers = "Ho5w ar7e y9ou3?";
List<char> noNumList = new List<char>();
foreach (var c in numbers)
{
if (!char.IsDigit(c))
noNumList.Add(c);
}
string noNumbers = string.Join("", noNumList);
If you want to remove all numbers from strings inside a collection :
List<string> myList = new List<string>() {
"Ho5w ar7e y9ou3?",
"W9he7re a3re y4ou go6ing?",
"He2ll4o!"
};
List<char> noNumList = new List<char>();
for (int i = 0; i < myList.Count; i++)
{
foreach (var c in myList[i])
{
if(!char.IsDigit(c))
noNumList.Add(c);
}
myList[i] = string.Join("", noNumList);
noNumList.Clear();
}
myList Output :
"How are you?"
"Where are you going?"
"Hello!"
I don't know exactly what is your scenario, but given a string, you can loop through its characters, and if it's a number, discard it from output.
Maybe this is what you're looking for:
string entry = "E#2";
char[] output = new char[entry.Length];
for(int i = 0, j =0; i < entry.Length ; i++)
{
if(!Char.IsDigit(entry[i]))
{
output[j] = entry[i];
j++;
}
}
Console.WriteLine(output);
I've tried to give you a simple solution with one loop and two index variables, avoiding string concatenations that can make performance lacks.
See this example working at C# Online Compiler
If i am not wrong,maybe this is how your list looks ?
ABCD123
EFGH456
And your expected output is :
ABCD
EFGH
Is that correct?If so,assuming that it's a List<string>,then you can use the below code :
list<string> mylist = new list<string>;
foreach(string item in mylist)
{
///To get letters/alphabets
var letters = new String(item.Where(Char.IsLetter).ToArray());
///to get special characters
var letters = new String(item.Where(Char.IsSymbol).ToArray())
}
Now you can easily combine the codes :)
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'm trying to add spaces between characters in a string in c#... Any advice would be very much appreciated.. Thanks
using System;
namespace nameReverser
{
class Program{
public static void Main(string[] args )
{ Console.WriteLine("Magical Name Reverser");
//User enters name
Console.WriteLine("Please Enter Your Name:");
string name = Console.ReadLine();
char[] cArray = name.ToCharArray();
string nameReversed = String.Empty;
for (int i= cArray.Length - 1; i>-1; i--)
{
nameReversed +=cArray[i];
}
Console.WriteLine("Your name in reverse order is:");
Console.WriteLine(nameReversed);
}
}
}
You can use String.Join to get a new string from array having a single space as separator. To print it in reverse order you can use Array.Reverse() hence your whole code will be like the following:
Console.WriteLine("Magical Name Reverser");
Console.WriteLine("Please Enter Your Name:");
string name = Console.ReadLine();
char[] cArray = name.ToCharArray();
Array.Reverse(cArray);
string resultString = String.Join(" ", cArray);
Console.WriteLine(resultString );
Console.WriteLine("Your name in reverse order is:");
Can be done in one-go
strResult= String.Join(" ", name.Reverse());
In addition to un-lucky's answer which adds spaces after each letter you can as well use the Insert() method of a string to add a space at a certain index
Example:
name = "Rudolf";
name.Insert (1, " ");
results to "R udolf"
Something like this
strResult= yourString(" ", name.Reverse());
Normally, I would recommend one of the other answers, if you only want to insert spaces into the string.
But in your example code, since you are looping through the string anyway, you can combine the reversal operation with the space insertion operation:
// ....
for (int i = cArray.Length - 1; i > -1; i--)
{
nameReversed += cArray[i] + " ";
}
// ...
Better yet, as suggested in the comments: if you are going to add to a string repeatedly, consider using a StringBuilder:
StringBuilder reverseBuilder;
for (int i = cArray.Length - 1; i > -1; i--)
{
reverseBuilder.Append(cArray[i]);
reverseBuilder.Append(' ');
}
// ...
nameReversed = reverseBuilder.ToString();
Slightly off subject...
If you want to add spaces between characters in a fixed width number like a time, you can also use the string format syntax:
int time = 1204; //represents 12:04
int hh = time / 100;
int mm = time - hh * 100;
string result = string.Format("{0:0 0} : {1:0 0}", hh, mm);
//result is 1 2 : 0 4
I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"