C# reversing Names - c#

I have to write a program were the user inputs the names (Aryah Stark, etc) and the otuput some to be Stark, Aryah. I cant seem to figure out why my code isn't coming out that way though. I know the Reverse. Array method but I don't know if I placing it right or not. Can someone help me?
class Program
{
static void Main(string[] args)
{
Console.WriteLine("How many names do you want to enter? ");
string name = Console.ReadLine();
int arraySize = Convert.ToInt32(name);
string[] LaName = new string[arraySize];
Array.Reverse(LaName);
for (int i = 0; i < LaName.Length; i++)
{
Console.WriteLine("Enter last name");
LaName[i] = Console.ReadLine();
}
foreach (string val in LaName)
{
Console.WriteLine(val + "\t");
}
Console.ReadKey();
}
}

Array.Reverse reverses a sequence of elements.
Based on example, what you need is reversing of a words in a string, so Split the string to words and then use Array.Reverse to reverse the array.
You could try using either of these solutions, place this logic inside your for loop (after reading user input).
string[] words = LaName[i].Split(' ');
Array.Reverse(words);
LaName[i] = String.Join(" ", words);
or simply (.Net 3.5 and aboeve)
LaName[i] =String.Join(" ", LaName[i].Split(' ').Reverse());
Check this Example

Related

What Is The Difference Between CharArray.ToString and new String(cArray)? [duplicate]

Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
code:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
output:
The output should say Word to guess: Hello.
Please will someone explain why this is happening as its not the first time I have run into this problem.
Calling ToString on a simple array only returns "T[]" regardless what the type T is. It doesn't have any special handling for char[].
To convert a char[] to string you can use:
string s = new string(charArray);
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
The constructor public String(char c, int count) repeats c count times.
The variable stars is an array of chars. This is the reason you get this error. As it is stated in MSDN
Returns a string that represents the current object.
In order you get a string from the characters in this array, you could use this:
Console.Write("Word to Guess: {0}" , new String(stars));
The correct way to do this would be:
string StarString = new string(stars);
ToString() calls the standard implementation of the Array-class's ToString-method which is the same for all Arrays and similarily to object only returns the fully qualified class name.
Try this code:
static string ConvertCharArr2Str(char[] chs)
{
var s = "";
foreach (var c in chs)
{
s += c;
}
return s;
}

Splitting an element of an array

In my C# program (I'm new to C# so I hope that I'm doing things correctly), I'm trying to read in all of the lines from a text file, which will look something along the lines of this, but with more entries (these are fictional people so don't worry about privacy):
Logan Babbleton ID #: 0000011 108 Crest Circle Mr. Logan M. Babbleton
Pittsburgh PA 15668 SSN: XXX-XX-XXXX
Current Program(s): Bachelor of Science in Cybersecurity
Mr. Carter J. Bairn ID #: 0000012 21340 North Drive Mr. Carter Joseph Bairn
Pittsburgh PA 15668 SSN: XXX-XX-XXXX
Current Program(s): Bachelor of Science in Computer Science
I have these lines read into an array, concentrationArray and want to find the lines that contain the word "Current", split them at the "(s): " in "Program(s): " and print the words that follow. I've done this earlier in my program, but splitting at an ID instead, like this:
nameLine = nameIDLine.Split(new string[] { "ID" }, StringSplitOptions.None)[1];
However, whenever I attempt to do this, I get an error that my index is out of the bounds of my split array (not my concentrationArray). Here's what I currently have:
for (int i = 0; i < concentrationArray.Length; i++)
{
if (concentrationArray[i].Contains("Current"))
{
lstTest.Items.Add(concentrationArray[i].Split(new string[] { "(s): " }, StringSplitOptions.None)[1]);
}
}
Where I'm confused is that if I change the index to 0 instead of 1, it will print everything out perfectly, but it will print out the first half, instead of the second half, which is what I want. What am I doing wrong? Any feedback is greatly appreciated since I'm fairly new at C# and would love to learn what I can. Thanks!
Edit - The only thing that I could think of was that maybe sometimes there wasn't anything after the string that I used to separate each element, but when I checked my text file, I found that was not the case and there is always something following the string used to separate.
You should check the result of split before trying to read at index 1.
If your line doesn't contain a "(s): " your code will crash with the exception given
for (int i = 0; i < concentrationArray.Length; i++)
{
if (concentrationArray[i].Contains("Current"))
{
string[] result = concentrationArray[i].Split(new string[] { "(s): " }, StringSplitOptions.None);
if(result.Length > 1)
lstTest.Items.Add(result[1]);
else
Console.WriteLine($"Line {i} has no (s): followeed by a space");
}
}
To complete the answer, if you always use index 0 then there is no error because when no separator is present in the input string then the output is an array with a single element containing the whole unsplitted string
If the line will always starts with
Current Program(s):
then why don't you just replace it with empty string like this:
concentrationArray[i].Replace("Current Program(s): ", "")
It is perhaps a little easier to understand and more reusable if you separate the concerns. It will also be easier to test. An example might be...
var allLines = File.ReadLines(#"C:\your\file\path\data.txt");
var currentPrograms = ExtractCurrentPrograms(allLines);
if (currentPrograms.Any())
{
lstTest.Items.AddRange(currentPrograms);
}
...
private static IEnumerable<string> ExtractCurrentPrograms(IEnumerable<string> lines)
{
const string targetPhrase = "Current Program(s):";
foreach (var line in lines.Where(l => !string.IsNullOrWhiteSpace(l)))
{
var index = line.IndexOf(targetPhrase);
if (index >= 0)
{
var programIndex = index + targetPhrase.Length;
var text = line.Substring(programIndex).Trim();
if (!string.IsNullOrWhiteSpace(text))
{
yield return text;
}
}
}
}
Here is a bit different approach
List<string> test = new List<string>();
string pattern = "Current Program(s):";
string[] allLines = File.ReadAllLines(#"C:\Users\xyz\Source\demo.txt");
foreach (var line in allLines)
{
if (line.Contains(pattern))
{
test.Add(line.Substring(line.IndexOf(pattern) + pattern.Length));
}
}
or
string pattern = "Current Program(s):";
lstTest.Items.AddRange(File.ReadLines(#"C:\Users\ODuritsyn\Source\demo.xml")
.Where(line => line.Contains(pattern))
.Select(line => line.Substring(line.IndexOf(pattern) + pattern.Length)));

How do I actually store the randomly chosen word as a word?

So I am working on a hangman program. It will pull from a list of 126 different words and randomly select one of the words. It will also output an "_" for each character.
But now, when I'm trying to determine the 'correct guess' of the word, I can't figure out how to actually store the value of the randomly chosen word. Sounds funny, but what have you. lol.
String[] myWordArrays = File.ReadAllLines("WordList.txt");
Random randomWord = new Random();
//int lineCount = File.ReadLines("WordList.txt").Count();
int activeWord = randomWord.Next(0, myWordArrays.Length);
string userSelection = "";
Console.WriteLine("Are you Ready to play Hangman? yes/no: ");
userSelection = Console.ReadLine();
if(userSelection == "yes")
{
foreach(char letter in myWordArrays[activeWord])
{
//the console.write(activeword) only shows the line number o.0.
//when I try to print out .Write(myWordArrays) it shows a
//System.(something) on the screen. ugh.
Console.Write(activeWord);
Console.Write("_ ");
}
I believe this is all the code that needs to be referenced as it is really the only code that deals with the choosing of the random word. I'm truly baffled by this. I've tried to set different things to the active word and I can't think of any logical way to have the 'foreach' also place each letter into an array (which would be beneficial later when I'm ready to search for each letter when the user guesses the letter).
the line that says
int activeWord = randomWord.Next(0, myWordArrays.Length);
change it to
String activeWord = myWordArrays[randomWord.Next(0, myWordArrays.Length)];
and change the foreach to
foreach(char letter in activeWord)
and you don't need to have the foreach put the word into a char array. When you need a char array, you can just say
activeWord.toCharArray()
But you probably won't even need that as String is IEnumerable, which means that you can do a foreach on a String, without turning it into an array, just like I did above.
Try this,
// Read the lines (words) from a file and store them in a list
String[] myWordArrays = File.ReadAllLines("WordList.txt");
// Generate a random number and select the word at that index of the list myWordArrays
Random randomWord = new Random();
int activeWord = randomWord.Next(0, myWordArrays.Length);
string randomlyChosenWord = myWordArrays[activeword];
// Query the user
Console.WriteLine("Are you Ready to play Hangman? yes/no: ");
string userSelection = Console.ReadLine();
// Initialize
if(userSelection == "yes")
{
foreach(char letter in randomlyChosenWord)
{
Console.Write("_ ");
}
}
Thank you to everyone, especially Marc B. Here is the solution that fixed it. Granted, it currently prints the random word as many times as there are chars in the word, but I'll fix that in a minute.
If you can see a more efficient manner of doing this, feel free to let me know!
private static void printWord()
{
String[] myWordArrays = File.ReadAllLines("WordList.txt");
Random randomWord = new Random();
//int lineCount = File.ReadLines("WordList.txt").Count();
int activeWord = randomWord.Next(0, myWordArrays.Length);
string userSelection = "";
string answerWord = myWordArrays[activeWord];
Console.WriteLine("Are you Ready to play Hangman? yes/no: ");
userSelection = Console.ReadLine();
if(userSelection == "yes")
{
//This runs through the randomly chosen word and prints an underscore in place of each letter - it does work
foreach(char letter in myWordArrays[activeWord])
{
Console.Write(answerWord);
Console.Write("_ ");
}
//This prints to the console "Can you guess what this 'varyingLength' letter word is?" - it does work.
}

How can you put single spaces into a string of characters in C#

I am still a beginner in C# and I know there is a method that can be used to do this but I can't seem to find it online.
I have a function that permutates a word
static void Main(string[] args)
{
string[] list = "a b c d".Split();
foreach (string[] permutation in Permutations<string>.AllFor(list))
{
System.Console.WriteLine(string.Join(" ", permutation));
}
}
However it only works with words that are broken up. (eg. "a b c d" ) Since that is not really a practical way to ask a user for input, I want to find a way to take a word from the user (an unbroken word like "hello" ) and break it up for the function to understand. Eg. form the input word of the use "happy" to a spaced word for the program to understand = "h a p p y"
I tried this code:
//splits the word into an array
string[] arr = name.Split();
//splits the array with spaces to enter into the program
name = string.Join(" ",arr);
arr = name.Split();
But it just ends up coming out unbroken anyway. Can someone tell me the easiest way to do this?
Just to mention I am still a beginner in C# and programming in total I might not understand some of the higher level concepts. I have been through some answers on this website and I have seen some answers that I don't understand at all.
You can loop over the string to convert it to an array, and then use Join.
using System.Text.RegularExpressions;
using System;
public class Program{
public static void Main(string[] args) {
string v = "hello";
// Convert into the a string array, the old-fashioned way.
string[] name = new string[v.Length];
for (int i = 0; i < v.Length; i++)
name[i] = v[i] + "";
string feedToPermutationFunction = string.Join(" ",name));
// Feed the above string into your permutation code.
}
}
You just need to separate each character and then concatenate them with a space:
This is the simplest way:
var userInput = Console.ReadLine();
var output = string.Join<char>(" ", userInput);
Console.WriteLine(output);
char[] array=input.ToArray();
string val="";
for(int i=0;i<array.Length;i++)
{
val+=array[i]+" ";
}
this will give you a string with spaces like you wanted Val
create an array with the string length
string[] strarray=new string[val.Length];
for(int i=0;i<strarray.Length;i++)
{
strarray[i]=val.Substring(i,len); //**i** is for string index,,,**len** string length in each index
}

String manuplation in C#

Is there any method that I can use that returns a fixed length array after spliting a string with some delimiter and fill the rest with a default string.
Eg.
string fullName = "Jhon Doe";
string[] names = fullName.SpecialSplit(some parameters); //This should always return string array of length 3 with the second elememnt set to empty if there is no middle name.
Next time specify the language you're asking about. We're no guessers.
In Java:
fullName.split(" ");
And anyway, no method will "return string array of length 3 with the second elememnt set to empty if there is no middle name". For the method, there are just two elements. You have to write that method yourself wrapping the standard split() method.
You should read over Jon Skeet's Writing the perfect question. It will be beneficial to you in the future when posting questions of StackOverflow.
There is no method in C# to do what you are asking, but you can easily write an extension method to do what I think you are asking.
here is a quick example:
public static class AbreviatorExtention
{
public static string[] GetInitials(this String str, char splitChar)
{
string[] initialArray = new string[3];
var nameArray = str.Split(new char[] { splitChar },
StringSplitOptions.RemoveEmptyEntries);
if (nameArray.Length == 2)
{
var charArrayFirstName = nameArray[0].ToCharArray();
var charArrayLastName = nameArray[1].ToCharArray();
initialArray[0] = charArrayFirstName[0].ToString().ToUpper();
initialArray[1] = string.Empty;
initialArray[2] = charArrayLastName[0].ToString().ToUpper();
}
else
{
for (int i = 0; i < nameArray.Length; i++)
{
initialArray[i] = (nameArray[i].ToCharArray())[1]
.ToString().ToUpper();
}
}
return initialArray;
}
}
class Program
{
static void Main(string[] args)
{
string FullName = "john doe";
//Extension method in use
string[] names = FullName.GetInitials(' ');
foreach (var item in names)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
}
Output:
J
D
I would set it up to split the string separate from the fixed array. If you still want a fixed array, then you set up the array to a size of three an populate. This is not the best method, however, as it has no meaning. Better, set up a person or user class and then populate, via rules, from the split string.

Categories