Use Substring method to count specific character from a string - c#

So I am new to programming and one of my exercises involves using a substring within a loop to count the number of iterations of a specific character with a user's input.
As far as I can tell for the exercise, and what I know in C sharp so far, using a substring in this will only help read the position of a character within the input, and will not count it. I can not make heads or tails of this, and am at a loss.
I want to know how to understand this, and what ways I am missing the point of the exercise.
I need an idea of how to set the substring to read the number of a certain character type from the end-user's input from console.
This is the original question:
There is a method called Substring that we can use with a string to look at a portion of a string.
For example, the following code will print the letter a.
string input = "abcdef";
Console.WriteLine(input.Substring(0, 1));
Assignment:
Given the following input, create a loop that uses the Substring method to count the number of times the letter ā€˜zā€™ occurs in a string input by the user.
asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza
Edit: So Far I have the code to count the number of times that Z is used, but I don't know how to incorporate a substring into it
int total = 0;
var letter = new HashSet<char> { 'z' };
Console.WriteLine("Please enter your letters:");
// asdfojiaqweb;ounqwrb;ounwqen;zzzn bnaozonza
string sentence = Console.ReadLine().ToLower();
for (int i = 0; i < sentence.Length; i++)
{
if (letter.Contains(sentence[i]))
{
total++;
}
}
Console.WriteLine("Total number of Z uses is: {0}", total);
// Console.WriteLine(sentence.Substring(0, 1));

If you must use Substring, then replace your loop by this
for (int i = 0; i < sentence.Length; i++)
{
if (sentence.Substring(i, 1) == "z")
{
total++;
}
}
And if you need to both count uppercase and lowercase z, then use following code
for (int i = 0; i < sentence.Length; i++)
{
if (string.Equals(sentence.Substring(i, 1), "z", StringComparison.OrdinalIgnoreCase))
{
total++;
}
}

Related

Is there such a thing as an array without size?

I am playing with C#. I try to write program that frames the quote entered by a user in a square of chars. So, the problem is... a user needs to indicate the number of lines before entering a quote. I want to remove this moment, so the user just enters lines of their phrase (each line is a new element in the string array, so I guess a program should kinda declare it by itself?..). I hope I explained clear what I meant x).
I've attached the program code below. I know that it is not perfect (for example, when entering the number of lines, I use the conversion to an integer, and if a user enters a letter, then this may confuse my electronic friend, this is a temporary solution, since I do not want to ask this x) The program itself must count these lines! x)) Though, I don't understand why the symbols on the left side are displayed incorrectly when the program displays output, but I think this also does not matter yet).
//Greet a user, asking for the number of lines.
Console.WriteLine("Greetings! I can put any phrase into beautiful #-square."
+ "\n" + "Wanna try? How many lines in the quote: ");
int numberOfLines = Convert.ToInt32(Console.ReadLine());
//Asking for each line.
string[] lines = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
Console.WriteLine("Enter the line: ");
lines[i] = Console.ReadLine();
}
//Looking for the biggest line
int length = 0;
for (int i = 0; i < numberOfLines; i++)
{
if (length < lines[i].Length) length = lines[i].Length;
}
//Starting framing
char doggy = '#';
char space = ' ';
length += 4;
string frame = new String(doggy, length);
Console.WriteLine(frame);
for (int i = 0; i < numberOfLines; i++)
{
string result = new string(space, length - 3 - lines[i].Length);
Console.WriteLine(doggy + space + lines[i] + result + doggy);
}
Console.WriteLine(frame);
Console.ReadLine();
}
}
}
There is performance gap and functionality between "Generic Lists" and arrays, you can read more about cons and pros of this two objects in the internet,
for example you can use list as Dai mentioned in comment like this
List<string> list = new List<string>();
list.Add("one");
list.Add("two");
list.Add("three");
or you can use arraylist
ArrayList arraylist = new ArrayList();
arraylist.Add();
or even you can change the size of array any times but it erase data in it
int[] arr = new int[100];
there is a function called ToArray() you can use it to change generic list to array
Your problem of the left side output is, that you add two values of char. This is not what you expect to be. You must convert the char to a string to append it to other strings:
Console.WriteLine(doggy.ToString() + space.ToString() + lines[i] + result + doggy.ToString());

Print ASCII of a triangle shape with variable input

Struggling with the print. I know it should be two for loops to print out the repeated letters, however, having problems to indent the lines. it should be a simple console C# program to print out the shape like below with a input 3.
XXXXX
XXX
X
With input 4 it should be like
XXXXXXX
XXXXX
XXX
X
Here is my code. Two for loops get the letters correctly but the lines all lined up at the left, not center.
static void Main(string[] args)
{
string num = Console.ReadLine().Trim();
int n = Convert.ToInt32(num);
int k=1;
for(int i = n; i>=1; i--)
{
Console.WriteLine("\n");
Console.WriteLine("".PadLeft(n));
for (int j = (2*i-1); j>=1;j--)
{
Console.Write("0");
}
}
Console.Read();
}
The statement:
Console.WriteLine("".PadLeft(n));
is the right idea but it's not quite there.
In your case, n is the number of lines you wish to print and is invariant. The number of spaces you need at the start of each line should begin at zero and increase by one for each line.
In any case, printing any number of spaces followed by newline (because it's WriteLine) is not what you want, you should be using Write instead.
So the code between int n = Convert.ToInt32(num); and Console.Read(); would be better off as something like:
for (int lineNum = 0; lineNum < n; lineNum++) {
int spaceCount = lineNum;
int xCount = (n - lineNum) * 2 - 1;
Console.Write("".PadLeft(spaceCount));
Console.WriteLine("".PadLeft(xCount, 'X'));
}
You'll notice some other changes there. First, I've used more meaningful variable names, something I'm a bit of a stickler for - using i is okay in certain circumstances but I often find it's more readable to use descriptive names.
I've also used PadLeft to do the X string as well, so as to remove the need for an inner loop.

How to get index of all matching chars in char array?

I am working on a simple hangman program. I have most of the code working, but I am having trouble figuring out how to get the index of multiple matching chars in a char array. For example, I have a word "sushi" converted to a char array. If the user guesses an "s" then all "s" in the char array should be shown. The way that my code is, I actually have two char arrays of the same length. The first array holds the chars of the word to guess, while the second array holds question marks. My code should iterate through the first array and return the index of each element in the array that matches the user guess. Then, the code inserts the user guess at each specified index and displays the second array for the user. Unfortunately, only the first occurrence is changed in the second array, so only the first index is returned from the match query. The problematic code is as follows:
//check if char array contains the user input
if (guessThis.Contains(Convert.ToChar(textBox1.Text)))
{
//save user input as char
char userGuess = Convert.ToChar(textBox1.Text);
//iterate through first char array
for (int i = 0; i < guessThis.Length - 1; i++ )
{
//check each element in the array
//probably don't need both for and foreach loops
foreach (char c in guessThis)
{
//get index of any element that contains the userinput
var getIndex = Array.IndexOf(guessThis, c);
//check if the element matches the user guess
if (c == userGuess)
{
//insert the userguess into the index
displayAnswer[getIndex] = userGuess;
}
}
}
//update the display label
answerLabel.Text = new string(displayAnswer);
SOLVED:
Working off of the example in the selected answer, I updated my code as:
//check if char array contains the user input
if (guessThis.Contains(Convert.ToChar(textBox1.Text)))
{
//save user input as char
char userGuess = Convert.ToChar(textBox1.Text);
string maybeThis = textBox1.Text;
string tryThis = new string(guessThis);
foreach (Match m in Regex.Matches(tryThis, maybeThis))
{
displayAnswer[m.Index] = userGuess;
}
answerLabel.Text = new string(displayAnswer);
}
Try Regex.Matches to build regex expression and find all matches and their positions.
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = "a*";
string input = "abaabb";
foreach (Match m in Regex.Matches(input, pattern))
Console.WriteLine("'{0}' found at index {1}.",
m.Value, m.Index);
}
}
// The example displays the following output:
// 'a' found at index 0.
// '' found at index 1.
// 'aa' found at index 2.
// '' found at index 4.
// '' found at index 5.
// '' found at index 6.`
http://msdn.microsoft.com/en-gb/library/system.text.regularexpressions.regex.matches(v=vs.110).aspx
Because your:
var getIndex = Array.IndexOf(guessThis, c);
always return the first occurance of character.
Your second for loop and the getIndex is useless, a clearer code could be:
for (int i = 0; i < guessThis.Length - 1; i++ )
{
//check if the element matches the user guess
if (c == userGuess[i])
{
//insert the userguess into the index
displayAnswer[i] = userGuess;
}
}
Also, your code allows user to input multiple characters into the textBox1. I think in this kind of game, only one character should be guessed each time. So I suggest your confine your input.
I think the problem is with the method:
var getIndex = Array.IndexOf(guessThis, c);
because it return the first location.
You can just use the index you have in the for loop
Try Something like this:
char userGuess = Convert.ToChar(textBox1.Text);
char[] displayAnswer = answerLabel.Text.ToCharArray();
for (int n = 0; n < displayAnswer.Length; n++)
{
if (guessThis[n] == userGuess)
{
displayAnswer[n] = userGuess;
}
}
answerLabel.Text = new string(displayAnswer);
A simple approach
You could do something like this (made generic for clarity):
public static IEnumerable<int> AllIndexesOfAny<T>(this IList<T> list, IEnumerable<T> ofAny)
{
return Enumerable.Range(0, list.Count).Where(i => ofAny.Contains(list[i]));
}
If performance becomes an issue, you could replace the IEnumerable<T> ofAny with a HashSet.
Update
Just read your code more closely and realized you are indexing through guessThis, and for each character in guessThis, finding its index in guessThis and checking whether it matches thisGuess. This is unnecessary. The simplest non-generic way to find all character indices in guessThis matching userGuess is probably:
var matches = Enumerable.Range(0, guessThis.Length).Where(i => guessThis[i] == userGuess);
Additional note
By the way, it probably doesn't matter for your application, but some non-ASCII Unicode characters in .Net are actually represented by surrogate pairs of chars. (There are also diacritical combining characters that modify the preceding character.) In an "internationalized" hangman game you might want to handle surrogate pairs by converting them to UTF32 code points:
public static IEnumerable<KeyValuePair<int, int>> Utf32IndexedCodePoints(this string s, int index)
{
for (int length = s.Length; index < length; index++)
{
yield return new KeyValuePair<int, int>(index, char.ConvertToUtf32(s, index));
if (char.IsSurrogatePair(s, index))
index++;
}
}

Comparing a string[index] to another string

I am in the process of learning C# and I'm building a hangman game from scratch as one of my first projects.
Everything works except for the part that replaces the dashes of the hidden word with the correctly guessed letters.
For example: ----- becomes G-EA- after you guess G, E, and A.
I have a for loop that logically seems like it'd do the job except I can't use the == operator for strings or chars.
for (int i = 0; i <= answer.Length; i++) //answer is a string "theword"
{
if (answer[i] == passMe) //passMe is "A" for example
{
hiddenWord = hiddenWord.Remove(i, 1);
hiddenWord = hiddenWord.Insert(i, passMe);
}
}
I've scoured the net trying to find a good solution. Most recommend using Regex or other commands I haven't learned yet and therefore don't fully understand how to implement.
I've tried converting both to char format in the hope that it would fix it, but no luck so far. Thanks in advance for any help.
If passMe is a string of only one char then
if (answer[i] == passMe[0])
In this way you compare the character at i-th position with the character at the first position of your user input
There is also a serious error in your code.
Your loop goes off by one, change it to
for (int i = 0; i < answer.Length; i++)
The arrays in NET start at index zero and, the max index value possible, is always one less than the length of the array.
answer[i] refers to a character and passMe is a single character string. (not a character)
Try this
for (int i = 0; i <= answer.Length; i++) //answer is a string "theword"
{
if (answer[i] == passMe[0]) //passMe is "A" for example
{
hiddenWord = hiddenWord.Remove(i, 1);
hiddenWord = hiddenWord.Insert(i, passMe);
}
}
you need to compare a character with a character.

whats wrong in this logic of finding longest common child of string

i came up with this logic to find longest common child of two strings of equal length but it runs successfuly only on simple outputs and fails others,pls guide me what i am doing wrong here.
String a, b;
int sum = 0;
int[] ar,br;
ar = new int[26];
br = new int[26];
a = Console.ReadLine();
b = Console.ReadLine();
for (int i = 0; i < a.Length; i++)
{
ar[(a[i] - 65)]++;
br[(b[i] - 65)]++;
}
for(int i =0;i<ar.Length;i++)
{
if (ar[i] <= br[i]) { sum += ar[i]; }
else sum += br[i];
}
Console.Write(sum);
Console.ReadLine();
output:
AA
BB
0 correct.
HARRRY
SALLY
2 correct
for both above input it runs but when i submit for evaluation it fails on their test cases.i cant access their testacase on which my logic fails.i wanna know where does my logic fails.
Your second loop is all wrong. It is simply finding the count of characters that occur in both the array and the count is only updated with the the no. of the common characters contained in the string containing the least no. of these common characters.
refer this link for the correct implementation.
http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Retrieve_the_Longest_Substring
Also convert your input to uppercase characters using String.ToUpper before you use the input string.

Categories