Count length of word without using Inbuilt functions - c#

This is a question I have come across and failed
Suppose say
string str = "wordcounter";
One can easily find the Length using str.Length
However, is it possible in C# to get the number of letters, without using any inbuilt functions like Length, SubStr etc

you could write a loop and increment a counter inside this loop:
int numberOfLetters = 0;
foreach (var c in str)
{
numberOfLetters++;
}
// at this stage numberOfLetters will contain the number of letters
// that the string contains
there is also another way:
int numberOfLetters = str.ToCharArray().Length;
there is also another, even crazier way using the SysStringByteLen function which operates on a BSTR. Strings in .NET are layed out in memory by using a 4 byte integer containing the length of the string followed by that many 2 byte UTF-16 characters representing each character. This is similar to how BSTRs are stored. So:
class Program
{
[DllImport("oleaut32.dll")]
static extern uint SysStringByteLen(IntPtr bstr);
static void Main()
{
string str = "wordcounter";
var bstr = Marshal.StringToBSTR(str);
// divide by 2 because the SysStringByteLen function returns
// number of bytes and each character takes 2 bytes (UTF-16)
var numberOfLetters = SysStringByteLen(bstr) / 2;
Console.WriteLine(numberOfLetters);
}
}
Obviously doing something like this instead of using the built-in Length function should never be done in any real production code and the code shown here should not be taken seriously.

My answer is bit late, but I would like to post the same. Though all above mentioned solutions are correct, but I believe that the IL of the foreach does knows about the length of the iterable before iterating it. Talking of a pure solution, here's mine:
private int stringLength(string str) {
int length = 0;
bool done = false;
do {
try {
char c = str[length];
length++;
} catch (IndexOutOfRangeException) {
done = true;
}
} while(!done);
return length;
}

How about?
int myOwnGetStringLength(String str)
{
int count = 0;
foreach(Char c in str)
count++;
return count;
}

not very fast but yo can always loop and count the number of caracter contained.
int counter = 0;
foreach (var caracter in str)
{
counter ++;
}

class Program
{
static void Main(string[] args)
{
string Name = "He is palying in a ground.";
char[] characters = Name.ToCharArray();
StringBuilder sb = new StringBuilder();
for (int i = Name.Length - 1; i >= 0; --i)
{
sb.Append(characters[i]);
}
Console.Write(sb.ToString());
Console.Read();
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a string to find its lenght");
string ch = Console.ReadLine();
Program p = new Program();
int answer = p.run(ch);
Console.WriteLine(answer);
Console.ReadKey();
}
public int run(string ch)
{
int count = 0;
foreach (char c in ch)
{
count++;
}
return count;
}
}

My general solution involves without using 'foreach' or 'StringBuilder' (which are C# specific) or without catching any exception.
string str = "wordcounter";
str += '\0';
int x = 0;
while (str[x] != '\0')
x++;
Console.WriteLine(x); //Outputs 11

class Program
{
static void Main(string[] args)
{
string test = "test";
//string as char array:
//iterate through char collection
foreach (char c in test)
{
//do something
}
//access elements by index
Console.WriteLine("Contents of char array : {0}, {1}, {2}, {3}", test[0], test[1], test[2], test[3]);
Console.ReadKey();
}
}

namespace ConsoleApplication {
class Program {
static void Main(string[] args) {
string testString = "testing";
int x = 0;
foreach(char c in testString) {
x++;
}
Console.WriteLine("\nLength Of String:{0}", (x));
Console.Read();
}
}

Related

How to bring each word letter in array c#

I have a problem in my code and I have no idea how to fix it. I need to copy every letter of the user entered word to array, but there is an error "Index was outside the bounds of the array". I know that thir error means that I don't have correct size of the array, but I am using ReadLine and I can't enter static size. It can be changed due user entered text.
Code:
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[] { };
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You should define length of str
static void Main(string[] args)
{
int c = 0;
string text = Console.ReadLine();
string[] str = new string[text.Length];//<-- NOTE THIS
foreach (char letter in text)
{
str[c] = Convert.ToString(letter);
Console.WriteLine(str[c]);
c++;
}
}
You can use Linq to make this a one-liner:
using System.Linq;
// ...
// ...
var separateLettersAsList = text.ToList();
var separateLettersAsArray = text.ToArray();

Random is not working good

I generate a string with 62 options ^ 6 letters = 56,800,235,584
But when running the code, it repeats the same string less then every 200,200 times
What is the problem here?
BTW:
This code is based on the answer here
class Program
{
static void Main(string[] args)
{
var d = new Dictionary<string, bool>();
for (int i = 0; ; i++)
{
var s = GenerateString(6);
try
{
d.Add(s, false);
}
catch (Exception ex)
{
Console.WriteLine(String.Format("{0} - {1} - {2}", i, s, ex.Message));
i = 0;
}
}
Console.ReadKey();
}
static Random _rnd = new Random();
public static string GenerateString(int len)
{
const string bigLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string smallLetters = "abcdefghijklmnopqrstuvwxyz";
const string numbers = "1234567890";
var validChars = bigLetters + smallLetters + numbers;
var result = new StringBuilder();
for (int i = 0; i < len; i++)
{
result.Append(validChars[_rnd.Next(validChars.Length)]);
}
return result.ToString();
}
}
There is all OK with random.
The problem is related with Birthday paradox. When you have 200k items one of them could repeat.
Random string doesnt garantee always unique result. For unique results you should use GUID's.
To avoid repeatation you can do a check for existence before adding the string to the list:
After for loop in GenerateString()
if(d.Contains(result.ToString()) // check whether the current generated string is in the list
{
GenerateString(len); // if it is already existed generate another one
}
else
{
return result.ToString(); // if not then return the string
}

Converting Character to Ascii

I've been creating a code breaking software and I need to convert the characters from a text file into ascii numbers to allow the shift. I have left my code below but could someone explain how I could do this?
using System;
using System.IO;
namespace CipherDecoder
{
class Program
{
static void Main(string[] args)
{
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
string cipherText = File.ReadAllText(fileText);
string output = #"C:\\Users\Samuel\Documents\Computer_Science\PaDS\output.txt\";
char[] cipherChars = new char[691];
int j = 0;
foreach (char s in cipherText)
{
cipherChars[j] = s;
j++;
}
for(int i = 0; i < cipherChars.Length; i++)
{
cipherChars[i] = cipherChars[i];
}
}
}
}
To get the int values into an int array you could just do this with as a LINQ select. For example:
string fileText = #"C:/Users/Samuel/Documents/Computer_Science/PaDS/caeserShiftEncodedText";
int [] charactersAsInts = File.ReadAllText(fileText).Select(chr => (int)chr).ToArray();
You can,
var asciiNumbersArray = cipherText.Cast<int>().ToArray();
If you cast a char to int you get the ascii number in decimal system.

C# Guessing Game using a text file

I'm trying to create a word guessing game that uses a dictionary text file. The game is supposed to take input from the user on how long the word should be before asking them to guess the word. If the user fails to guess after 3 times then it reveals the answer. I used a list on recommendation from a friend to read from the dictionary as it is quite large.
My question is, how can I read the list to choose a word for the guessing game?
{
static int letterLength, LettersLeft, wrongGuess;
public static void Main(string[] args)
{
string input = System.IO.File.ReadAllText("dictionary.txt");
string[] terms = input.Split();
List<string> list = new List<string>();
for (int num = 0; num < terms.Length; num++)
list.Add(terms[num]);
int wordToGuess = GetLengthOfWordToGuess();
List<string> fixedlist = new List<string>();
for (int num = 0; num < list.Count; num++)
{
string tempword = list[num];
if (tempword.Length == wordToGuess)
fixedlist.Add(tempword);
}
for (int num = 0; num < fixedlist.Count; num++)
Console.WriteLine(fixedlist[num]);
Console.WriteLine("Welcome to the guessing game");
letterLength = GetLengthOfWordToGuess();
Console.Clear();
//Not Working from here on.
string wordGuess = GetWordToGuess();
char[] maskedWord = GetHiddenLetters(wordGuess, '-');
LettersLeft = wordGuess.Length;
char userGuess;
wrongGuess = 3;
while (wrongGuess > 0 && LettersLeft > 0)
{
DispayCharacters(maskedWord);
Console.WriteLine("Enter a Letter");
userGuess = char.Parse(Console.ReadLine());
maskedWord = CheckGuess(userGuess, wordGuess, maskedWord);
}
Console.WriteLine("Well done! Thanks for Playing.");
Console.ReadLine();
}
static string GetWordToGuess()
{
Random word = new Random();
int wordNumber = word.Next(0, 9);
string[] words = { "" };
string selectWord = words[wordNumber];
return selectWord;
}
static char [] GetHiddenLetters(string word, char mask)
{
char[] hidden = new char[word.Length];
for (int i = 0; i < word.Length; i++)
{
hidden[i] = mask;
}
return hidden;
}
static void DispayCharacters(char [] characters)
{
foreach(char letter in characters)
{
Console.Write(letter);
Console.WriteLine();
}
}
static int GetLengthOfWordToGuess()
{
Console.WriteLine("Input length of word to guess");
int selectWord = int.Parse(Console.ReadLine());
return selectWord;
}
static char [] CheckGuess (char letterToCheck, string word, char [] characters)
{
bool wrong = true;
if(wrongGuess > 0)
{
for (int i = 0; i < word.Length; i++)
{
if (word[i] == letterToCheck)
{
characters[i] = word[i];
LettersLeft--;
wrong = false;
}
}
}
}
}
One major problem I see up front is that your GetWordToGuess function is not functional and probably throws an IndexOutOfRangeException.
The reason for that is that you are instantiating the words array as an array with a single empty string in it, but you are then referencing an index between 0 and 9, which will not exist in that array unless the random number generated is 0.
To solve this you should pass the fixedlist List you already created and use that instead of the words array. You should make sure to generate a random number between 0 and fixedlist.Count-1 so that you don't hit that same out of range exception. Therefore that function should look something like this:
static string GetWordToGuess(List<string> fixedlist)
{
Random word = new Random();
int wordNumber = word.Next(0, 9);
string[] words = { "" };
string selectWord = words[wordNumber];
return selectWord;
}
Also, as it stands right now, your included code doesn't compile because the CheckGuess function doesn't return a char[] as it says it should. I believe what you meant to do was have a return characters; line at the end (this was probably just a copy paste issue when you put your code in your question, but I thought I'd mention it just in case).
As a side note there are a number of small issues with your code like declaring things you don't use, but since they don't break your program I didn't want to go through and fix them.

List all of the "A"'s in string

I wanted to count all of the "A's" in a paritcular string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace TESTING
{
class Testing
{
static void Main(string[] args)
{
//ask user for the filename
string userInput = fetchFileName("Enter the textfile you want to view: ");
//test if the filename writes anything to console
string fileContents = File.ReadAllText(userInput);
string theFileContents = analyseFile(fileContents);
// Console.WriteLine(theFileContents);
Console.ReadLine();
}
private static string analyseFile(string fileContents)
{
string str = fileContents;
if (str.Contains("A"))
{
Console.WriteLine("YES");
}
else
{
Console.WriteLine("NO");
}
return str;
}
private static string fetchFileName(string askFileName)
{
Console.WriteLine(askFileName);
string userAnswer = Console.ReadLine();
return userAnswer;
}
}
}
Take a look at LINQ. It allows to perform whole range of operations on any kind of collection. And a string is a collection of chars. Below an example how LINQ can make your life easier:
string text = "A sdfsf a A sdfsf AAS sdfA";
int res = text.Count(letter => letter == 'A');
What happens here is that you take text and provide a predicat saying that you want to take any variable letter from the string such that the letter is equal to char A. Then you want to count them.
One of the easiest ways is to iterate over all characters in your file and check if the letter is equal to the letter you want.
When you realize that a string is nothing more then an array of characters, you can do something like this:
public int LetterCount(string filename, char letter)
{
int cnt = 0;
string source = File.ReadAllText(filename);
//Check every character in your string; if it matches increase the counter by 1
foreach (char c in source)
{
if(c == letter)
{
cnt++;
}
}
return cnt;
}
And use it like this:
int A_count = LetterCount(#"C:\test.txt", 'A');
Please note, that this code does not check, if the file actually exists. If you put in a wrong path, you end up with a FileNotFoundException.
Foreach is just another type of loop. This could just as easily be done with a for-loop. The trick is to split the string up in individual characters that you can later compare.
I'm sure you will figure out how to implement this if I just set you on the right path:
string test = "My name is Isak";
char[] arrayOfChars = test.ToCharArray();
int count = 0;
for (int i = 0; i < arrayOfChars.Length; i++)
{
if (arrayOfChars[i] == 'a' || arrayOfChars[i] == 'A')
{
count++;
}
}
try simple as
string test = "ABBCDABNDEAA";
int Count = test.Count(x => x == 'A');
Using LINQ, this can by really simple:
string myString = "ababsgsdfsaaaAA22bbaa";
var count = myString.ToLower().Count(c => c == 'a');
Console.Write(count);
Here we take the string and convert it to all lower case so that A and a will be counted together. Then we use the simple LINQ method Count() to count the number of a characters there are.
You could use linq
string text = "The quick brown fox jumps over the lazy dog";
var count = text.ToLower().Where(x => x == 'a').Count();
Console.WriteLine(count);
But if you cannot use any advanced techniques you could do it like this:
string text = "The quick brown fox jumps over the lazy dog";
int counter = 0;
for (int i = 0; i < text.Count(); i++)
{
if (text[i] == 'a' || text[i] == 'A')
{
counter++;
}
}
Console.WriteLine(counter);
You can do this:
string stringValue = "Addsadsd AAf,,werAA";
int qtdChar = stringValue.Count(x => x == 'A');
int qtdCharInsensitive = stringValue.Count(x => x == 'A' || x=='a');
If you do not want to use a foreach you could erase all the letter A's and compare the length difference.
A bit like this :
private static string analyseFile(string fileContents)
{
var strippedString = fileContents.Replace("A","");
var count = fileContents.Length - strippedString.Length;
return count.ToString();
}

Categories

Resources