How can i get the total occurrence of letter K? [duplicate] - c#

This question already has answers here:
Number of occurrences of a character in a string [duplicate]
(6 answers)
Closed 6 years ago.
I want to check on how many times does k appears. this is
what i have done so far and am not getting the results.
class Program
{
static void Main(string[] args)
{
int count = 0;
string str = "hnfdjkkedjjykukyukrtrnrkkkkt";
string l;
for (int i = 0; i < str.Length; i++)
{
l = str.Substring(1, 1);
if (l == "k")
{
count++;
}
}
Console.WriteLine("k appears " + count++ + " times");
Console.ReadKey();
}
}

You can try :
int count = str.Count(c => c=='k')
Hope this help :-)

You can go as simple as
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string s = "aasfkkfasfas";
int count = s.Count(l => l== 'k');
Console.WriteLine(count);
}
}
Calling Substring for each letter is really not the best solution. Keep in mind that string implements IEnumerable so you can also do it like this:
using System;
public class Program
{
public static void Main()
{
string s = "aasfkkfasfas";
int count = 0;
foreach(char c in s)
{
if(c == 'k')
count++;
}
Console.WriteLine(count);
}
}
This is closer to your original solution.

You can also use RegEx (Regular Expressions) for that but it's kind of overkill for your use case.
It's found in the namespace System.Text.RegularExpressions (see MSDN).
Regex.Matches(text, pattern).Count
In your case, it would be
Regex.Matches("hnfdjkkedjjykukyukrtrnrkkkkt", "[k]").Count

Related

I just get System.IndexOutOfRangeException [duplicate]

This question already has answers here:
Reverse word of full sentence
(20 answers)
Closed 2 years ago.
I've been tried to do an algorithm that ask for a sentence and put the words backwards, for example if I insert "Cookies and milk" it would give back "milk and Cookies", but it gives me System.IndexOutOfRangeException in the second for. Please help
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string sentence;
string spac = " ";
char[] phr;
char space = char.Parse(spac);
Console.WriteLine("Write a sentence");
sentence = Console.ReadLine();
phr = sentence.ToCharArray();
for (int i = phr.Length-1; i >= 0; i--)
{
if (phr[i] == space)
{
for (int j = i++; phr[j] != phr.Length-1 || phr[j]!=space; j++)
{
Console.WriteLine(phr[j]);
}
}
}
}
}
}
You can split a string into an array based on any character. If you split by space you can keep the words intact. Do this, then reverse the order, and join it again.
string sentence = "Cookies and Milk";
string wordsReversed =
string.Join(" ",
sentence.Split(' ').Reverse()
);
Console.WriteLine(wordsReversed); // "Milk and Cookies"

Return all powers of 2 less then n in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For a given number n, I need to return all powers of 2 less than n, as a string in a way that elements are separated with "-". If n < 2, it needs to return an empty string.
For example:
n = 20 => 1-2-4-8-16
n = 8 => 1-2-4
I'm a beginner, so any help would be much appreciated! :)
EDIT: this is not working
using System;
class N
{
static int[] powerof2(int n)
{
int[] array = new int[n];
if (n < 2)
return new int[0];
for (int i = 0; i < 8 * sizeof(uint); i++)
{
int curr = 1 << i;
if (curr > n)
break;
array[i] = curr;
}
return array;
public override string ToString()
{
for (int i = 0; i < array.length; i++)
return (array[i] + "-");
}
}
static public void Main ()
{
int n = 10;
Console.WriteLine(powerof2(n).ToString());
}
}
You need to run the for loop with the following rule
for (int i = 1; i < n; i *= 2)
Whole solution
class Program
{
static void powerof2(int n)
{
if (n < 2)
Console.WriteLine(string.Empty);
for (int i = 1; i < n; i *= 2)
{
if (i > 1)
Console.Write("-");
Console.Write(i);
}
}
static void Main(string[] args)
{
powerof2(20);
}
Using iterator methods makes this case trivial (Fiddle):
using System;
using System.Collections.Generic;
public class Program
{
public static IEnumerable<int> GetPowersOf2(int maxN)
{
for (int p = 1; p < maxN; p *= 2)
{
yield return p;
}
}
public static void Main(string[] args)
{
IEnumerable<int> powersOf2LessThan20 = GetPowersOf2(20);
Console.WriteLine(string.Join("-", powersOf2LessThan20));
}
}
I suppose this is what you're looking for:
class Program
{
public static string Pow2LessThan(ulong n)
{
if (n < 2)
return "";
// start with 2^0
string res = "1";
// try further
int p = 1;
ulong cnum = 2;
while (cnum < n)
{
res += "-" + cnum.ToString();
++p;
cnum = (ulong)(1 << p);
}
return res;
}
static void Main(string[] args)
{
ulong n = 20;
Console.WriteLine(Pow2LessThan(n));
Console.ReadLine();
}
}
The reason that it's not working is: you never access the class N in any way. The call should be
Console.WriteLine(N.powerof2(n).ToString());
^^
With that modification, you'll be notified that the method powerof2() is inaccessible due to its protection level. You need to make it at least internal like so:
internal static int[] powerof2(int n)
Next, note that you're missing a } for that method.
return array;
}
With that fixed, the compiler will tell you that you can't access array inside ToString(), because the scope of array is limited to powerof2(). Make the array a field of the class like
static int[] array;
Now, the compiler complains about array.length in ToString(). Fix that by capitalizing Length.
Mistake number 6: ToString() will return in the first iteration of the loop. It will not return anything if array.Length is 0. The function should look a little bit like this:
public override string ToString()
{
string result = "";
for (int i = 0; i < array.Length; i++)
result += array[i] + "-";
return result;
}
Now, this will still not work, because the main method calls ToString() on the return value of powerof2(), which is of type int[] and not of type N. That's because your stuff is static. Make it non-static instead and create an instance of N.
static public void Main ()
{
var n = new N();
n.powerof2(10);
Console.WriteLine(n.ToString());
}
With 7 issues fixed, the output is now 1-2-4-8-0-0-0-0-0-0-, so there's still stuff to fix. Maybe you get a little bit of a feeling why everyone proposes a totally different solution.
What else to fix:
the output of course is still incorrect.
if someone inputs 4000000000 as the number, you certainly don't want to allocate 4 GB of RAM in the array.
Why allocate an array at all and not construct the string right away?
Why 8*sizeof(uint)? You can't shift more often than sizeof(uint).
class Program
{
static string powerof2(int n)
{
var str="1" ;
if (n < 2)
return "" ;
else
{
var i=1;
while(Math.Pow(i, 2)<n)
{
str+="-" +Math.Pow(2, i);
i++;
}
return str;
}
}
static void Main(string[] args)
{
powerof2(50);
}
}

C#. How do I write a function that can search a string within a string and return the number of occurrences? [duplicate]

This question already has answers here:
How would you count occurrences of a string (actually a char) within a string?
(34 answers)
Closed 6 years ago.
I need some help figure this one out. I need to search a string within a string and return the number of occurrences. I have tried the code below and it works and i also tried to use a regex and it worked but my teacher said to pretend that i can't use the indexOf or the regex. I know there have been some similar questions but that didn't help me much since they all use IndexOf or regex. So any ideas please?
What I have tried:
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string s1 = "hellohjhghello";
string s2 = "he";
var r = Occurrences(s1, s2);
Console.WriteLine("{0} is repeated {1} times", s2, r);
}
static int Occurrences(string s1, string s2)
{
int count = 0;
int pos = 0;
while((pos = s1.IndexOf(s2,pos)) > -1)
{
count++;
pos += s2.Length;
}
return count;
}
}
}
EDIT:
I don't know what my teacher expects me to so but in another exercise I did a search for a char in string. He said to do something similar but for a string. My previous exercise goes like this:
class ex3
{
static void Main(string[] args)
{
string str = "aaabekldfj";
char letter = 'a';
var r = Occurrences(str, letter);
Console.WriteLine("The letter '{0}' from string '{1}' has {2} occurrences", letter, str,r);
}
static int Occurences(string str, char letter)
{
int repeat = 0;
for(int i=0; i< str.Length; i++)
{
if (str[i] == letter)
repeat++;
}
return repeat;
}
}
Why not keep it simple?
string compareText = "hello! This is a string to check hello's in this string!";
string compareWord = "hello";
int occurrences = (compareText.Length - compareText.Replace(compareWord, string.Empty).Length) / compareWord.Length;
Without indexof and regex and keeping it simple (but not fast), you can do following
static int OccurrencesAdvanced(string s1, string s2)
{
var result = 0;
for (var i = 0; i <= (s1.Length - s2.Length); i++)
{
var tested = s1.Substring(i, s2.Length);
if (string.Compare(tested, s2) == 0)
{
i += Math.Max(1, s2.Length - 1);
result++;
}
}
return result;
}
Here is my idea what first came in my mind. I don't know currently where are you in your studies so this solution might not good for you.
class Program
{
static void Main(string[] args)
{
var s1 = "hellohjhghello";
var s2 = "lo";
var occurence = 0;
Occurrences(s1, s2, ref occurence);
Console.WriteLine("{0} is repeated {1} times", s2, occurence);
Console.ReadLine();
}
static void Occurrences(string s1, string s2, ref int occurence)
{
var index = s1.IndexOf(s2);
if (index > -1)
{
occurence++;
s1 = s1.Substring(index + s2.Length);
Occurrences(s1, s2, ref occurence);
}
}
}

In C#, How can I determine if a given string is a palindrome or not? [duplicate]

This question already has answers here:
Check if a string is a palindrome
(33 answers)
Closed 6 years ago.
I'm currently wondering if when a given string (word), how can I determine if it is a palindrome or not. A palindrome is a word or phrase that is the same if read forward or backward. I think I can solve this by looping through the half the word and comparing each letter with the other half. An example for this could be: (word[0] == word[word.Length-1-0]) would compare the first letter with the last letter of word, and (word[1] == word[word.Length-1-1]) would compare the second letter with the second to last letter.
Example Input could be: racecar
Example Output: True
Am I approaching this problem correctly towards the proper solution?
Here's a bit of I've written down so far.
public bool Test6(string word)
{
for (int i = 0; i < word.Length; i++)
{
if (word[0] == word[word.Length - 1 - 0])
{
}
I would do this (quickly).
string input = "..."
string reverse = new string(input.ToCharArray().Reverse().ToArray());
if(input.Equals(reverse)
{
// polindrome.
}
Please follow this link http://www.dotnetperls.com/palindrome
You can do it using this example without using any built in method :
using System;
class Program
{
public static bool IsPalindrome(string value)
{
int min = 0;
int max = value.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char a = value[min];
char b = value[max];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
min++;
max--;
}
}
static void Main()
{
string[] array =
{
"civic",
"deified",
"deleveled",
"devoved",
"dewed",
"Hannah",
"kayak",
"level",
"madam",
"racecar",
"radar",
"redder",
"refer",
"repaper",
"reviver",
"rotator",
"rotor",
"sagas",
"solos",
"sexes",
"stats",
"tenet",
"Dot",
"Net",
"Perls",
"Is",
"Not",
"A",
"Palindrome",
""
};
foreach (string value in array)
{
Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
}
}
}
A shorter version using LINQ would be
bool IsPalindrome(string x)
{
return Enumerable.Range(0,x.Length/2).All(e => x[e] == x[x.Length-1-e]);
}
Please find the code below
using System;
using System.Linq;
class MyClass
{
static void Main(string[] args) {
string str = Console.ReadLine();
string backwardsGuy = new string(str.Reverse().ToArray());
if(str==backwardsGuy)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
}
}
Sample code-
static void Main(string[] args)
{
string s,revs="";
Console.WriteLine(" Enter string");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0; i--) //String Reverse
{
revs += s[i].ToString();
}
if (revs == s) // Checking whether string is palindrome or not
{
Console.WriteLine("String is Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
else
{
Console.WriteLine("String is not Palindrome \n Entered String Was {0} and reverse string is {1}", s, revs);
}
Console.ReadKey();
}

Create a list of strings from A to BBB in C#

Morning all,
I have a simple question that I could do with some help with.
I need to create a list of strings that will start with A and finish at some other point e.g BBB, but I am not sure the best and fastest way of doing it.
Thanks in advance.
Ok as requested more information.
I need to create a simple way of creating a list of bays for a warehouse. This wareshouse can have a variable number of Aisles in it, a variable number of rows in each aisle and a variable number of bins for the row. So when the user comes to setup their particular warehouse they can specify the start letter of the Aisle and the end letter of the Aisle.
As you can now see the hardcoded list from A to ... isn't going to work.
No error checking (start number could be greater than end number in which case you would get an infinite loop) but the code works fine.
Hope you at least understand it before submitting it!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testList
{
class Program
{
static void Main(string[] args)
{
Console.Write((int)'A');
Console.Write((int)'Z');
Console.WriteLine("Whats the starting string?");
string start = Console.ReadLine().ToUpper();
Console.WriteLine("Whats the end string?");
string end = Console.ReadLine().ToUpper();
List<string> retVal = new List<string>();
retVal.Add(start);
string currentString = start;
while (currentString != end)
{
currentString = IncrementString(currentString);
Console.WriteLine(currentString);
retVal.Add(currentString);
}
retVal.Add(end);
Console.WriteLine("Done");
Console.ReadKey();
}
private static string IncrementString(string currentString)
{
StringBuilder retVal = new StringBuilder(currentString);
char endChar= currentString[currentString.Length - 1];
for (int x = (currentString.Length - 1); x >= 0; x--)
{
char c = currentString[x];
if (TryIncrementChar(ref c))
{
retVal[x] = c;
break;
}
else
{
retVal[x] = 'A';
if (x == 0)
{
retVal.Insert(0,'A');
}
}
}
return retVal.ToString();
}
private static bool TryIncrementChar(ref char currChar)
{
if (currChar != 'Z')
{
currChar++;
return true;
}
return false;
}
}
}

Categories