This program prints all possibilities of a string input, for example, if input is abc', the output should be the combinations, this works but when im creating the arraylist it's printing out numbers instead of the string combinations, code:
string input = Console.ReadLine();
int sl = input.Length;
ArrayList arr = new ArrayList();
for (int three = 0; three < sl; three++) {
for (int two = 0; two < sl; two++) {
for (int one = 0; one < sl; one++) {
char onef = input[one];
char twof = input[two];
char threef = input[three];
arr.Add(threef + twof + onef);
Console.Write(threef);
Console.Write(twof);
Console.WriteLine(onef);
}
}
}
Console.WriteLine("The elements of the ArrayList are:");
foreach(object obj in arr) {
Console.WriteLine(obj);
}
the output of the arraylist is numbers and not the string chars, help!
Just change these three lines
From:
char onef = input[one];
char twof = input[two];
char threef = input[three];
To:
string onef = input[one].ToString();
string twof = input[two].ToString();
string threef = input[three].ToString();
Alternate: change one line:
arr.Add(string.Format("{0}{1}{2}", a, b, c));
char cannot be concatenated like string. The + is interpreted numerically.
Related
I'm trying to receive an integer of 40 characters as a string from the console and iterate over each element in that string and then save it as an element in an array of int's. this is not working and just returns 49 50 51 as array members.
public HugeInteger(string myString)
{
for (int i = 0; i < 39; i++)
{
int t = Convert.ToInt16(myString[i]);
this.myInteger[i] = t;
}
}
Since you are trying to convert chars '0' .. '9' to integers, you just need to subtract the character code for '0' from each character, like so:
public HugeInteger(string myString)
{
for (int i = 0; i < 39; i++)
{
char c = myString[i];
// Remove the next `if` (and its body) if error checking is not required.
if (c < '0' || c > '9')
throw new InvalidOperationException("Non-digit in input");
this.myInteger[i] = c - '0';
}
}
This works because:
The character codes for '0' to '9' are 48 .. 57
If you subtract '0' from a character code, you are effectively subtracting 48 from it.
Therefore subtracting '0' from a digit character will yield the int equivalent.
Note that there is no error checking in your loop, so if the string contains any non-digit characters, the result will be wrong!
If you want the string to be converted to an array i would suggest that you convert the string to char array and then convert back to int[] like below:
class Program
{
static void Main(string[] args)
{
string myString = "1231654165152112315461561561651561562165";
var charArray = myString.ToCharArray();
foreach (var item in charArray)
{
Console.WriteLine(item);
}
int[] myStringIntegers = Array.ConvertAll(charArray, c => (int)Char.GetNumericValue(c));
Console.WriteLine(myStringIntegers.Length);
int i = 0;
foreach (var item in myStringIntegers)
{
Console.WriteLine("Value at pos("+i+") : " + item);
i++;
}
Console.Read();
}
}
if you have multi digit numbers then i would say that you have the myString value separated by a comma ',' or space or whatever you like.
CAUTION : If the value is non-numeric then it will result in code failure. So you need to make a regex check or some sort of validation to address non-numeric inputs
Below is 2 simple ways of extracting an array of integers from a string.
Converting char to int.
Converting a split string to int.
This may not be the best or most elegant solution but you can get some idea on how you would want to approach your problem.
class Program
{
static void Main(string[] args)
{
Console.Write("Input str: ");
string str = Console.ReadLine();
int[] numbers = StringToIntArray(str);
foreach(int num in numbers)
{
Console.WriteLine(num);
}
Console.Write("Input str: ");
str = Console.ReadLine();
Console.Write("Input split char: ");
ConsoleKeyInfo splitChar = Console.ReadKey();
numbers = StringToIntArray(str, splitChar.KeyChar);
Console.WriteLine();
foreach (int num in numbers)
{
Console.WriteLine(num);
}
Console.ReadKey();
}
public static int[] StringToIntArray(string str, char? splitChar = null)
{
List<int> numbers = new List<int>();
if (splitChar.HasValue)
{
string[] split = str.Split(splitChar.Value);
foreach(string splitStr in split)
{
int parsedInt = 0;
if (int.TryParse(splitStr, out parsedInt))
{
numbers.Add(parsedInt);
}
}
}
else
{
foreach (char c in str)
{
int parsedInt = 0;
if (int.TryParse(c.ToString(), out parsedInt))
{
numbers.Add(parsedInt);
}
}
}
return numbers.ToArray();
}
}
Output:
If your input is like this :
"1 2 3 4"
You should split it with ' ' or else you should separate your numbers with a separator.
List<int> myInteger=new List<int>();
public void HugeInteger(string myString)
{
foreach (string value in myString.Split(' '))
{
myInteger.Add(int.Parse(value));
}
}
Without seperator you should iterate by this way:
foreach (char c in myString)
{
myInteger.Add(int.Parse(c.ToString()));
}
static void Main(string[] args)
{
Console.WriteLine("Input number");
string myStr = Console.ReadLine();
int[] intNums = new int[40];
string flag = "";
for (int i = 0; i < myStr.Length; i++)
{
int a = 1;
flag = myStr.Substring(i, a);
a = i;
intNums[i] = Convert.ToInt32(flag);
a = i;
}
foreach (var item in intNums)
{
if (item > 0)
{
Console.Write(item+",");
}
}
Console.ReadKey();
}
IF you take an input you should sub-string the string, convert each part to an int, and then store in the array. Not sure a 40 character long integer would work just with the number bits even int64 can handle
This question already has answers here:
Finding longest word in string
(4 answers)
Closed 3 years ago.
I got an assignment to make a method to find the longest word in a string without split, distinct and foreach.
I was able to split the words and count the length but I am stuck on how can I actually compare and write them out.
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
longestWord(s1);
Console.
}
static void longestWord(String s1)
{
char emp = ' ';
int count = 0;
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
count++;
Console.Write(" " + (count-1));
Console.WriteLine();
count = 0;
}
else
{
Console.Write(ee[i]);
count++;
}
}
}
The output right now looks like this:
Alex 4
has 3
2 1
hands 5
I am pretty sure I would be able to get only the longest number to show by comparing count before reset with temp int but how to write out the word with it.
Or if there is a easier way which probably is.
You are already on a good way. Instead of directly printing the words, store the length and position of the longest word and print it at the end. Like so:
static void longestWord(String s1)
{
char emp = ' ';
int longestLength = 0;
int longestStart = 0;
int currentStart = 0;
for (int i = 0; i < s1.Length; i++)
{
if (s1[i] == emp || s1[i] == '.')
{
// calculate the current word length
int currentLength = i - currentStart;
// test if this is longer than the currently longest
if(currentLength > longestLength)
{
longestLength = currentLength;
longestStart = currentStart;
}
// a new word starts at the next character
currentStart = i + 1;
}
}
// print the longest word
Console.WriteLine($"Longest word has length {longestLength}: \"{s1.Substring(longestStart, longestLength)}\"");
}
There is no need for the .ToCharArray(). You can access the string directly.
I will question whether you are actually supposed to treat "2" as a word and count it at all. Using regular expressions will allow you to approach the problem using a LINQ one-liner:
static void Main(string[] args)
{
String s1 = "Alex has 2 hands.";
var word = longestWord(s1);
Console.WriteLine(word);
//Console.ReadLine();
}
static string longestWord(string s1) {
return Regex.Matches(s1,"[A-Za-z]+") // find all sequences containing alphabetical characters, you can add numberas as well: [A-Za-z0-9]
.Cast<Match>() // cast results to Enumberable<Match> so we can apply LINQ to it
.OrderByDescending(m => m.Length) // luckily for us, Match comes with Length, so we just sort our results by it
.Select(m => m.Value) // instead of picking up everything, we only want the actual word
.First(); // since we ordered by descending - first item will be the longest word
}
You can store for every word the chars in new list of chars (list for dynamic length)
and if the new word is longer of the prev long word convert it to string.
If you have two word in same length it will take the first.
If you want the last change the "maxLength < count" to "maxLength <= count"
static string longestWord(String s1)
{
char emp = ' ';
int count = 0;
int maxLength = 0;
string maxWord = string.Empty;
List<char> newWord = new List<char>();
char[] ee = s1.ToCharArray();
for (int i = 0; i < ee.Length; i++)
{
if (ee[i] == emp || ee[i] == '.')
{
if (maxLength < count)
{
maxLength = count;
maxWord = new string(newWord.ToArray());
}
count = 0;
newWord = new List<char>();
}
else
{
newWord.Add(ee[i]);
count++;
}
}
return maxWord;
}
I want to create a password list.
So far, it works but my list contains only words like D?t1g3+T%J.
Now I want to create words with more sense.
I have a List with words like Banana, Desk and so on.
How is it possible to change randomly the spelling, add numbers and special characters?
For example:
"Banana" -> "baNana123"
Well, I have just come up with this.
string foo = "banana";
List<string> chars = new List<string>();
Random rnd = new Random();
string newPassword = "";
for (int i = 0; i < foo.Length; i++)
{
chars.Add(foo[i].ToString());
}
foreach (var boo in chars)
{
var randomNum = rnd.Next(0, 2);
Debug.WriteLine(randomNum);
if (randomNum == 0)
{
newPassword = newPassword + boo.ToUpper();
}
else
{
newPassword = newPassword + boo.ToLower();
}
}
Debug.WriteLine(newPassword);
What it does: 1)strips the string, in my case "banana" into individual characters
2) for every character program generates randomly 1, or 0. Base on that I just simply convert to lower, or upper case.
All you have to do is to feed the algorithm with strings. And to the adding numbers at the end you can do something like this I quess.
int howMany = rnd.Next(1, 20); //1 to 19 numbers, you can set that manually
for (int i = 0; i < howMany; i++)
{
newPassword = newPassword + rnd.Next(0, 10);
}
Debug.WriteLine(newPassword);
Outcome last run for me: BanANA6469242684
I have a situation where users can assign locations to items.
locations range from A1 to GG17
I guess it is like a row / column format.. Columns Range from A - GG. After Z will be STRICTLY AA, BB, CC, DD, EE, FF, GG.
And rows 1-17
i.e. users can assign location A1, A2, A3, B4, AA1, BB2... GG17
I want to validate the text the user enters when they assigning a location to stop them from adding HH1 or A20 for example..
I am able to achieve this from A - Z, 1-17, but am stumbling when the validation has to go past Z (AA, BB, CC...)
this is what I have for A-Z and 1-17 so far that works
List<char> allowedColumns = new List<char>();
List<int> allowedRows = new List<int>();
char column ='A';
int row = 1;
if (txtAssignLocation.Text != "")
{
while (column <= 'Z')
{
allowedColumns.Add(column);
column++;
}
while (row <= 17)
{
allowedRows.Add(row);
row++;
}
string enteredText = txtAssignLocation.Text;
string enteredColumn = enteredText.Substring(0, 1);
string enteredRow = enteredText.Substring(1);
if (!allowedColumns.Contains(Convert.ToChar(enteredColumn)) || !allowedRows.Contains(Convert.ToInt32(enteredRow)))
{
lblValidationError.Text = "Entered Location does not exist";
}
}
I am at a bit of a loss since Char cannot be more than one character and it and ++ cannot be applied to string
new Regex("^[A-Z][A-G]?[1-9][0-7]?$") validates most of the combinations. Preventing the numbers from 20 to 97 is a bit more tricky. But play around with regular expressions or just split the string and to an int.TryParse and make sure that the number part is <= 17.
EDIT
Yes, it was a bit quick'n'dirty. This one should do the trick:
#"^([A-Z]|([A-G])\2)([1-9]|1[0-7])$"
Example usage:
Regex regex = new Regex(#"^([A-Z]|([A-G])\2)([1-9]|1[0-7])$");
string userInput = "AG20";
bool ok = regex.Match(userInput).Success;
Based on what David said in the comments why not simply have a "hard coded" list of acceptable values since there aren't that many and simply check any entered text against this list?
// This will be a list of all valid locations from 'A1' to 'GG17'
var locations = new HashSet<string>();
// Add all values from 'A1' to 'Z17'
for (char c = 'A'; c <= 'Z'; c++)
{
for (int i = 1; i <= 17; i++)
{
locations.Add($"{c}{i}");
}
}
// Add the values for 'AA1' to 'GG17'
for (char c = 'A'; c <= 'G'; c++)
{
for (int i = 1; i <= 17; i++)
{
locations.Add($"{c}{c}{i}");
}
}
Now you can simply check against this list for validation:
locations.Contains("A1"); // true
locations.Contains("BB10"); // true
locations.Contains("AF7"); // false
locations.Contains("GA10"); // false
You can do this with just providing the maxColumn and maxRow in your method (or passed in as variables) instead of an array or other hardcoding of logic. You could enhance this with LINQ, but providing answer as a loop for clarity:
public static bool ValidateInput(string input)
{
//set maxColumn and maxRow sizes
const string maxColumn = "BG";
const int maxRow = 155;
//initialize input parse variables
string inputColumn = "";
int inputRow = int.MaxValue;
//use only upper-case (to aid in comparison)
input = input.ToUpper();
//parse input into inputColumn and inputRow
for (int i = 0; i < input.Length; i++)
{
if (char.IsDigit(input[i]))
{
inputRow = int.Parse(input.Substring(i));
break;
}
inputColumn += input[i];
}
//make sure the length is at least as long as maxColumn (for comparing single letter column to double-letter column, for example)
inputColumn.PadLeft(maxColumn.Length, ' ');
//return comparison result (inclusive to maxColum and maxRow)
return string.Compare(inputColumn, maxColumn) <= 0 && inputRow <= maxRow;
}
UPDATE: If you are interested in the LINQ version, here it is:
public static bool ValidateInput(string input)
{
//set maxColumn and maxRow sizes
const string maxColumn = "BG";
const int maxRow = 155;
//parse input into inputColumn and inputRow
string inputColumn = new string(input.TakeWhile(char.IsLetter).Select(char.ToUpper).ToArray());
int inputRow = int.Parse(new string(input.Skip(inputColumn.Length).ToArray()));
//make sure the length is at least as long as maxColumn (for comparing single letter column to double-letter column, for example)
inputColumn.PadLeft(maxColumn.Length, ' ');
//return comparison result (inclusive to maxColum and maxRow)
return string.Compare(inputColumn, maxColumn) <= 0 && inputRow <= maxRow;
}
I am trying to create a string that inserts a duplicate letter from the original into the modified. For example, the output of one run would be:
Original word:
stack
Output:
sstack, sttack, staack, stacck, stackk
Does that make sense? I have this so far, and I feel i am close, but I am suing the wrong method to reassemble the string. Any help would be appreciated:
// Use ToCharArray to convert string to array.
char[] array = originalWord.ToCharArray();
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
string result = array.ToString();
string result2 = string.Join("", result.Select(x => x + letter));
Console.Write(result2);
}
This should work:
var original = "stack";
for (int i = 0; i < original.Length; i++)
Console.WriteLine(original.Insert(i, original[i].ToString()));
You can use String.Insert to insert a string at a given index into another string.
IEnumerable<string> strings = originalWord
.Select((c, idx) => originalWord.Insert(idx, c.ToString()));
Fixed :
string originalWord = "stack";
// Use ToCharArray to convert string to array.
char[] array = originalWord.ToCharArray();
// Loop through array.
for (int i = 0; i < array.Length; i++)
{
// Get character from array.
char letter = array[i];
string result = originalWord.Insert(i, letter.ToString(CultureInfo.InvariantCulture));
Console.WriteLine(result);
}
The Linq way :
IEnumerable<string> words = originalWord.Select((letter, i) => originalWord.Insert(i, letter.ToString(CultureInfo.InvariantCulture)));
You can use String.Insert() method like;
string s = "stack";
for (int i = 0; i < s.Length; i++)
{
Console.WriteLine (s.Insert(i, s[i].ToString()));
}
Here is a DEMO.
Oh god, already aded 3 answers when I writing it. Damn..