how to call String array method in main in c# - c#

I am new to c# and I don't understand why this isn't working. i am getting Error is subjects() in main as mentioned below.
My code is the following:
class Program
{
static void Main(string[] args)
{string sub;
// string brd;
brd = board();
sub = subjects(); // Error
//Console.WriteLine(brd);
Console.WriteLine(sub);
Console.ReadLine();
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
int[] index = new int[limit];
for (limit = 0; limit <= index.Length; limit++)
{
Console.WriteLine("Please Enter Subject Name " + limit + 1);
Subjects[limit] = Console.ReadLine();
}
return Subjects;
}
}

Try this:
string[] sub = subjects();
Instead of this:
string sub;
sub = subjects();
Because you are getting a string of array and passing it to a normal string.

Please refer to /**/ comment
class Program
{
static void Main(string[] args)
{
string sub; /*1. Remove this line*/
// string brd;
brd = board();
sub = subjects(); /*2. string[] sub = subjects();*/
//Console.WriteLine(brd);
Console.WriteLine(sub);
Console.ReadLine();
}
public static string[] subjects()
{
Console.WriteLine("Please Enter How many Subject Do you Want to input");
int limit = System.Convert.ToInt32(Console.ReadLine());
string[] Subjects = new string[limit];
int[] index = new int[limit]; /*3. Remove this line -> Redundant*/
/*4. Change variable `limit` to `i`*/
for (int i = 0; i <= limit; i++)
{
Console.WriteLine("Please Enter Subject Name " + i + 1);
Subjects[i] = Console.ReadLine();
}
return Subjects;
}
}

You are defining sub as string (string sub) but the method subjects is returning a string array. Sosubis not able to hold the return value from that method. you have to change the return type ofsubfrom string tostring[]`. That means the declaration should be like this:
string[] sub = subjects();
Or in much easier way you can make it like this:
var sub = subjects();
So the compiler will automatically choose the return type based on the return value from that method. If you are confused about the datatype in such assignments you can var let compiler decide the datatype based on the values.

Now there is not any Error in the code but in run time error compiler is not printing (sub)
Console.WriteLine(sub);
Console.ReadLine();

Related

Applying grammar to strings

I'm trying to make the genetive of the inserted name be decided automatically so that I won't have to manually insert the proper genetive for each string (in this case names)
As an example the genetive for James is ' and the genetive for Kennedy is 's.
I guess what I'm trying to say is that I want a cleaner implementation that allows me to skip having to write string Genetive:friend1(2..n) for each name
using System;
namespace Prac
{
class Program
{
static void Main(string[] args)
{
string Friend = ""; string last_char_Friend = ""; string Genetive_Friend = "";
string Friend1 = "Kennedy"; string last_char_Friend1 = Friend1[^1..]; string Genetive_Friend1 = "\'s";
string Friend2 = "James"; string last_char_Friend2 = Friend2[^1..]; string Genetive_Friend2 = "\'";
string Friend3 = "Ngolo Kante"; string last_char_Friend3 = Friend3[^1..]; string Genetive_Friend3 = "\'s";
Console.WriteLine($"My friends are named {Friend1}, {Friend2} and {Friend3}");
Console.WriteLine($"{Friend1}{Genetive_Friend1} name has {Friend1.Length} letters");
Console.WriteLine($"{Friend2}{Genetive_Friend2} name has {Friend2.Length} letters");
Console.WriteLine($"{Friend3}{Genetive_Friend3} name has {Friend3.Length} letters");
for (int i = 1; i < 4; i++)
{
Console.WriteLine($"{Friend + i}{Genetive_Friend + i} name has {(Friend + i).Length} letters");
}
Console.ReadLine();
}
}
}
There simply must be a smarter way for me to ensure that proper grammar is applied to each name, I've got a feeling that I can utilize reading the last char of the Friend string, but how do I within Console.WriteLine pick betweem ' and 's?
I'd like the for loop to print the same as the three individual Console.WriteLine lines.
Also this is my first time asking a question on Stackoverflow, please tell me if I've broken some unwritten rule on how questiosn should be formatted.
Theres a few questions here, firstly to loop through all the arguments you should create an Array (Or list or really anything extending IEnumerable)
then you can iterate over it.
now following your example and not being particularly versed in grammar you can also write a method to check what is the last character of the input string and convert it into the genitive case
static void Main( string[] args )
{
string[] friends = new string[] { "Kennedy", "James", "Ngolo Kante" };
Console.WriteLine($"My friends are named {JoinEndingWithAnd(friends)}");
for ( int i = 1; i < friends.Length; i++ )
{
Console.WriteLine( $"{MakeGenitive(friends[i])} name has {friends[i].Length} letters" );
}
Console.ReadLine();
}
static string JoinEndingWithAnd(string[] friends)
{
string result = friends[0];
for ( int i = 1; i < friends.Length; i++ )
{
if ( i != friends.Length - 1)
{
result += $" , {friends[i]}";
}
else
{
result += $" and {friends[i]}";
}
}
return result;
}
static string MakeGenitive(string friend)
{
char lastLetter = friend[^1];
if( lastLetter == 's' )
{
return friend + "'";
}
return friend + "'s";
}

Dynamically create variables from splitting string c#

I am making a web service for an app with Tesseract Ocr 3.02.
I want to create variables on depending of how many informations I get on the business card and after that classify information from a string.
For example:
Tel. +496123456789$Mobil +49123456789$kai.kalsbach#gmail.com$www.google.com$Kai Kalsbach$Muster Str 1a$40599 Düsseldorf$"
And then like this:
-Telephone number
-First Name
-Last Name
-Email
-Address
That was my first idea:
string endText1 = text.Split('$')[0];
string endText2 = text.Split('$')[1];
string endText3 = text.Split('$')[2];
string endText4 = text.Split('$')[3];
string endText5 = text.Split('$')[4];
string endText6 = text.Split('$')[5];
string endText7 = text.Split('$')[6];
string endText8 = text.Split('$')[7];
and after that i would classify the variables.
but in many cases I get the following exception because the number of informations can vary depending of business card.
System.IndexOutOfRangeException: Index was outside the bounds of the array c#
The IndexOutOfRangeException exception is thrown because the code tries to access an item outside the array length.
My proposition : I created formattedArray with contains always 8 items and I copied the splited array to this formattedArray. With that, you have no more IndexOutOfRangeException because the item missing in text.Split('$') is null in formattedArray
var a = text.Split('$');
var formattedArray = new string[8];
Array.Copy(a, formattedArray, a.Length);
string endText1 = formattedArray [0];
string endText2 = formattedArray [1];
string endText3 = formattedArray [2];
string endText4 = formattedArray [3];
string endText5 = formattedArray [4];
string endText6 = formattedArray [5];
string endText7 = formattedArray [6];
string endText8 = formattedArray [7];
string[] Splitted = text.Split('$');
And you mentioned you want to make a decision based on the number of elements the split spits out
int Count = Splitted.Length;
switch(Count)
{ case 0: //DoStuff
break;
....
default:
break;
}
In your case, it is better to use the following:
string[] stringList = text.Split('$');
foreach(string val in stringList)
{
//your logic.
}
You can split the string once using the .Split method.
Then afterwards run it in a foreach or for loop. I believe your logic is based on the amount of strings, so you are looking for a 'for' loop.
string[] split = text.Split('$');
for (int i = 0; i < split.Length; i++)
{
var text = split[i];
// Your logic here...
switch (i) // for logic based on the index of the string
{
case 0:
// do something
break;
case 1:
// do something
break;
}
}
The IndexOutOfRangeException exception is thrown because the code tries to access the 8th item in a 7-item array :
string endText8 = text.Split('$')[7];
Indexes in .NET collections are 0-based which means 7 refers to the 8th element.
By default, String.Split will return empty fields as well. This means that either the string isn't the same as the one posted here, or that the StringSplitOptions.RemoveEmptyEntries was used
String.Split returns a string array that can be stored in a string[] variable. There's no need to repeat String.Split, or use multiple variables :
var items = text.Split(new[]{'$'},StringSplitOptions.RemoveEmptyEntries);
Creating a class from this array is simple enough that you probably don't need to create a custom parser :
class Record
{
public string Telephone {get;set;}
...
}
var items = text.Split('$');
var record=new Record
{
Telephone=items[0],
Mobile=items[1],
...
};
Another easy way to do that is to use a try, then all variables will be created until the index has reached its maximum.
string[] strArray = text.Split('$');
Try {
string endText1 = strArray[0];
string endText2 = strArray[1];
string endText3 = strArray[2];
string endText4 = strArray[3];
string endText5 = strArray[4];
string endText6 = strArray[5];
string endText7 = strArray[6];
string endText8 = strArray[7];
}
catch
{
//nothing
}
Create factory and recognizers
public class PhoneItem : IItem
{
public PhoneItem(string text)
{
// some code
}
}
public interface IRecognizer
{
IItem Recognize(int index, string text);
}
public class PhoneRecognizer : IRecognizer
{
public IItem Recognize(int index, string text)
{
return index == 0 ? new PhoneItem(text) : null;
}
}
public class ItemFactory
{
private IEnumerable<IRecognizer> _recognizers = new []
{
new PhoneRecognizer(),
new FullNameRecognizer()
};
public IItem CreateItem(int index, string text)
{
foreach (var rec in _recognizers)
{
var item = rec.Recognize(index, text);
if (item != null)
{
return item;
}
}
throw new Exception("Item not recognized");
}
}
Split string to pieces
var parts = text.Split('$');
Use the factory to create objects
var factory = new ItemFactory();
var items = new List<IItem>();
for (int i = 0; i < parts.Length; i++)
{
items.Add(factory.CreateItem(i, parts[i]));
}
// do whatever you wants

Getting variable type and variable info from Console.WriteLine

Basically I'm trying to make it so I can do
Console.WriteLine("variable : value");
var stuff = Console.ReadLine();
And then use the first word of "stuff" to be the variable type int,string etc. and the rest of the line to be what the variable's value is, so like
string testing this
would make a variable i made into a string and the value be "testing this"
string stuff = Console.ReadLine(); // get the input in string
string[] stuffSplit = stuff.Split(' '); // split by space char
string firstStuff = stuffSplit[0]; // the first word
string theRestOfStuff = string.Join(" ", stuffSplit.Skip(1)); // the rest of the words combined with space again
Maybe something like this?
static void Main(string[] args)
{
int integerNumber;
double doubleNumber;
var stuff = Console.ReadLine();
bool isInteger = int.TryParse(stuff, out integerNumber);
bool isDouble = double.TryParse(stuff, out doubleNumber);
if(isInteger)
Console.WriteLine(integerNumber.GetType() + stuff);
else if(isDouble)
Console.WriteLine(doubleNumber.GetType() + stuff);
else
{
Console.WriteLine(stuff.GetType() + stuff );
}
Console.ReadLine();
}
You get the idea.
try this
var inputText = Console.ReadLine();
string stuff = string.Empty;
if(inputText != null && inputText.IndexOf(':') > 0)
{
stuff = inputText.Substring(inputText.IndexOf(':')+2, inputText.Length)
}

using do while statement in method returning string

I am writing a program for shopping system. In this I am using array to get input from the brand name from the user. I am using method which returns string to get the input. Following is code:
public class Brand{
private string brandName;
public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
public string getBrandName()
{
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
string temp = Console.ReadLine();
do
{
try
{
for (int i = 0; i < 6; i++)
{
if (brands[i].Contains(temp))
{
this.BrandName = temp;
break;
}
}
return this.BrandName;
}
catch
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
}
} while (BrandName!=temp);
}
}
The problem is that I am at beginner level and not getting the trick what should be in this while statement that it loops and asks user to input again and again until he enters the correct brand name. Please help me.
Maybe this will work based on your code:
public string getBrandName()
{
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
string temp = Console.ReadLine();
while(!brand.Contains(temp))
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
temp = Console.ReadLine();
}
return temp;
}
Few things to notice:
We will ask the user for a brand name.
We will check that the input is a brand from brands list (you use contains to check if the input is in the char array of every brand name, watch the difference).
If then name is in the list we will not enter inside the loop and we
will return the brand name.
If the name is not in the list we will ask the user again to insert a
valid brand name until he will enter any and then we will return it.
if you have only 4 no of brands then you can try or statement for all of them in while loop
while (input== 'brand1'||'brand2')
or if your list is too big then you can put them in an arraylist
like this
List <String> listClone = new ArrayList<String>();
for (String string : list) {
if(string.matches("(?i)(bea).*")){
listClone.add(string);
}
}
System.out.println(listClone);
You have an outOfRange exception here :
for (int i = 0; i < 6; i++)
beacuse there is out of range from the array where brands[5].
The function contains return true or false when the input string is substring of the specified string and not equel !!!
You arrive to this row only if has exception:
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
Check the following code - it work well :
class Program
{
static void Main(string[] args)
{
Brand brand = new Brand();
string brandName = brand.getBrandName();
Console.WriteLine("You enter correct brand name !!!");
Console.WriteLine(brandName);
Console.ReadLine();
}
public class Brand
{
private string brandName;
public string BrandName
{
get { return brandName; }
set { brandName = value; }
}
public string getBrandName()
{
bool isValid = false;
string temp = "";
string[] brands = new string[5];
brands[0] = "Honda";
brands[1] = "Suzuki";
brands[2] = "Ferrari";
brands[3] = "BMW";
brands[4] = "Toyota";
Console.WriteLine("Please enter the brand name from the above given brands..");
while (!isValid)
{
for (int i = 0; i < brands.Length; i++)
{
Console.WriteLine(brands[i]);
}
temp = Console.ReadLine();
for (int i = 0; i < brands.Length; i++)
{
if (brands[i] == temp)
{
this.BrandName = temp;
isValid = true;
break;
}
else
{
isValid = false;
}
if (i == brands.Length - 1)
{
Console.WriteLine("Your provide brand does not match with the database in our system. Please try another one.");
}
}
}
return temp;
}
}
}

display format for results in console

I am trying to display my results as follows:
-.-|- [tab] kt
-.|-- [tab] nm
-.|-|- [tab] ntt
But this is my current output
-.-|-| kt
-.|--| nm
-.|-|-| [tab]ntt
There is a | at the end of every Morse code which I would like to remove since it is at the end.
Also because the user can input Morse code with space between dots and dashes - i noticed that it affects the alignment of the characters and not all of them get tabbed properly. The word tab isn't supposed to show i just wrote it in because I didn't know how to place a real tab.
private static readonly IDictionary<char, string> morseCode_alpha = new Dictionary<char, string>
{
{'a', ".-"},{'b',"-..."}, {'c',"-.-."}, {'d',"-.."}, {'e',"."},
{'f',"..-."}, {'g',"--."}, {'h',"...."},{'i',".."}, {'j',".---"},
{'k',"-.-"}, {'l',".-.."}, {'m',"--"}, {'n',"-."}, {'o',"---"},
{'p',".--."}, {'q',"--.-"}, {'r',".-."}, {'s',"..."}, {'t',"-"},
{'u',"..-"}, {'v',"...-"}, {'w',".--"}, {'x',"-..-"}, {'y',"-.--"}, {'z',"--.."}
};
private static string ConvertMorseToText(string symbolCode)
{
var builder = new StringBuilder(4 * symbolCode.Length);
foreach (char c in symbolCode)
builder.Append(morseCode_alpha[c]);
return builder.ToString();
}
private static string ConvertTextToMorse(char ch)
{
if (morseCode_alpha.Keys.Contains(ch))
return morseCode_alpha[ch];
else
return string.Empty;
}
private static string ConvertStringToMorse(string letters)
{
StringBuilder sb = new StringBuilder();
foreach (char ch in letters)
{
if (sb.Length != 0 && sb[sb.Length - 1] != ' ')
sb.Append("|");
sb.Append(ConvertTextToMorse(ch));
}
return sb.ToString();
}
private static IEnumerable<string> Permutations( string symbolCode)
{
int n = symbolCode.Length;
if (n == 0 || symbolCode.Length == 0)
yield return " ";
else
foreach (var entry in morseCode_alpha)
if (symbolCode.StartsWith(entry.Value))
foreach (string next in Permutations(symbolCode.Substring(entry.Value.Length)))
yield return entry.Key + next;
}
private static void Write( string rest)
{
string result = ConvertStringToMorse(rest);
Console.Write(result+"\t");
Console.WriteLine(rest);
}
static void Main(string[] args)
{
string morseInput;
string entered = "";
do
{
Console.WriteLine("Enter Morse Code: \n");
morseInput = Console.ReadLine().Replace(" ","");
bool isValid = Regex.IsMatch(morseInput, #"^[-.]+$");
if (isValid)
{
Console.WriteLine("\nAll permutations:\n");
string morse = ConvertMorseToText(entered);
string permutations = morseInput.Substring(morse.Length);
Write(permutations);
var nexts = new List<string>(Permutations(permutations));
foreach (string next in nexts)
Write(next);
}
else
{
Console.WriteLine("\nFormat of morse must be only dots and dashes.");
Console.WriteLine("Parameter name: "+morseInput+"\n");
}
}
while (morseInput.Length != 0);
}
And, to answer the other part of the question...
Tabstops are fixed for console writing, so it would be better to use something like String.PadRight
so, your code could be:
private static void Write(string rest)
{
string result = ConvertStringToMorse(rest);
Console.Write(result.PadRight(20));
Console.WriteLine(rest);
}
Draft version of the method:
private static string ConvertStringToMorse(string letters)
{
var result = string.Join("|",
letters
.Select(ConvertTextToMorse)
.Where(morse => !string.IsNullOrEmpty(morse)));
return result;
}
Update:
Please note that the entered variable is used only once: when defined - empty string is assigned. Then the ConvertMorseToText(entered) method is called: it always returns empty string for the empty string argument. After this assignment string permutations = morseInput.Substring(morse.Length); the permutations variable will store exactly the same value as morse variable (because morse.Length is always 0).
So, it seems that the entered variable and the ConvertMorseToText() method are useless (both can be safely removed):
static void Main(string[] args)
{
do
{
Console.WriteLine("Enter Morse Code: ");
string morseInput = Console.ReadLine();
if (string.IsNullOrWhiteSpace(morseInput))
{
// Empty or consists only of white-space characters
break;
}
morseInput = morseInput.Replace(" ", "");
bool isValid = Regex.IsMatch(morseInput, #"^[-.]+$");
if (isValid)
{
Console.WriteLine("All permutations:");
Console.WriteLine();
var nexts = Permutations(morseInput).ToList();
foreach (string next in nexts)
Write(next);
}
else
{
Console.WriteLine();
Console.WriteLine("Format of morse must be only dots and dashes.");
Console.WriteLine("Parameter name: {0}", morseInput);
}
}
while (true);
}
Update 2:
Consider using TryGetValue() method of Dictionary<TKey, TValue> instead of Keys.Contains and [] (indexer) i.e. do not perform look-up twice:
private static string ConvertTextToMorse(char ch)
{
string result;
return morseCode_alpha.TryGetValue(ch, out result) ? result : string.Empty;
}
Instead this code:
Console.Write(result+"\t");
Console.WriteLine(rest);
Use
Console.WriteLine("{0,-10}{1,-10}", result, rest);
Then you will see two columns (each max 10 charachters) with left alignment. Or remove "-" sign if you want right alignment.

Categories