c# : string length without predefined function - c#

I am writing a code to find out the total length of string in c#.
code is as follow
class Program
{
static void Main(string[] args)
{
string str = "Amit Kumar";
int c = 0;
for(int i = 0; str[i]!="\n"; i++)
{
c++;
}
Console.WriteLine(c);
Console.ReadLine();
}
}
but it showing != operator can not be applied to operands on char or string type.
can you solve my problem

You can't compare a string to a char using != as stated in the error. So use '\n' instead. But anyways, your string doesn't contain the newline character and would never terminate.
We can make your code work with some modifications. Use foreach to loop over the characters in the string.
class Program
{
static void Main(string[] args)
{
string str = "Amit Kumar";
int c = 0;
foreach(char x in str)
{
c++;
}
Console.WriteLine(c);
Console.ReadLine();
}
}
I hope this is just for education, as there's built in functions to tell you the length of a string.

You need this code:
class Program
{
static void Main(string[] args)
{
string str = "Amit Kumar";
int c = 0;
foreach(char x in str)
{
if (str[i] != '\n')
c++;
}
Console.WriteLine(c);
Console.ReadLine();
}
}

mason's answer is perfectly fine, but here's an alternative:
void Main()
{
string str = "Amit Kumar";
int c = 0;
while(str != "")
{
str = str.Substring(1);
c++;
}
Console.WriteLine(c);
Console.ReadLine();
}
This method successively removes characters until it's left with the empty string, then prints the number of characters removed. But just for fun, this can be rewritten as
void Main()
{
string str = "Amit Kumar";
int c = 0;
while(str.Substring(++c) != "") /* do nothing */;
Console.WriteLine(c);
Console.ReadLine();
}

Related

Recursive reversing string C#

I don't know how i don't want a direct answer I want to know how can i.
Many thanks in advance.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a word or sentence to be reversed: ");
string str = Console.ReadLine();
Console.WriteLine("**********");
Console.WriteLine("Your input is: ");
Console.WriteLine(str);
Console.ReadLine();//to give a little bit space between the outputs
Console.WriteLine("************");
Console.WriteLine("And it will be reversed as : ");
//call the Recursive Function in the class Recursive
str = Recursive.Recursive_Func(str);
Console.WriteLine(str);
Console.ReadLine();
}
}
We use Substring to print from the n-1 index in the string
and end it with the first index in the string which is [0].
class Recursive
{
public static string Recursive_Func(string str)
{
if (str.Length <= 1) //the program base case
{
return str;
}
else
{
return Recursive_Func(str.Substring(1)) + str[0];
}
}
}
I believe this solution is simpler and easier to understand than the other answer.
public static string MyReverse(string s)
{
if (s.Length == 1)
{
return s;
}
var firstLetter = s[0];
return MyReverse(s.Substring(1)) + firstLetter;
}
Your implementation is naïve and slow but it is recursive, and it works. The below implementation converts the string into a char array, uses a recursive helper method to reverse the chars in-place, and converts the reversed array back into a string:
class Recursive
{
public static string StrRev(string s)
{
if (string.IsNullOrEmpty(s)) return s;
var a = s.ToCharArray();
return new string(CharArrRev(a, 0, a.Length - 1));
}
private static char[] CharArrRev(char[] a, int i, int j)
{
if (i >= j) return a;
var c = a[i]; a[i] = a[j]; a[j] = c;
return CharArrRev(a, i + 1, j - 1);
}
}

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);
}
}
}

Delegates with return type multicast gives unexpected result

I was trying to learn delegate multicasting and wrote this sample program :
delegate string strDelegate(string str);
class strOps
{
public static string reverseString(string str)
{
string temp = string.Empty;
for(int i=str.Length -1 ; i>=0 ; i--)
{
temp += str[i];
}
return temp;
}
public string removeSpaces(string str)
{
string temp = string.Empty;
for (int i = 0; i < str.Length; i++)
{
if (str[i] != ' ')
temp += str[i];
}
return temp;
}
}
// calling the code in main method
string str = "This is a sample string";
strOps obj = new strOps();
strDelegate delRef = obj.removeSpaces;
delRef += strOps.reverseString;
Console.WriteLine("the result of passing This is a sample string \n {0}", delRef(str));
I expected it to return the reversed string without spaces , instead it ONLY reverses string and gives this output :
gnirts elpmas a si sihT
Can anybody please point me in the right direction to understand this.
Any help will be appreciated.
Thanks.
A combined delegate will only return the result of the last invoked method. From the documentation:
If the delegate has a return value and/or out parameters, it returns
the return value and parameters of the last method invoked
The multicast delegate will still invoke both methods assigned to it. If you change your methods to print the value before returning it, you'll see it clearly:
void Main()
{
string str = "This is a sample string";
strOps obj = new strOps();
strDelegate delRef = obj.removeSpaces;
delRef += strOps.reverseString;
delRef(str);
}
delegate string strDelegate(string str);
class strOps
{
public static string reverseString(string str)
{
string temp = string.Empty;
for(int i=str.Length -1 ; i>=0 ; i--)
{
temp += str[i];
}
Console.WriteLine("Output from ReverseString: {0}", temp);
return temp;
}
public string removeSpaces(string str)
{
string temp = string.Empty;
for (int i = 0; i < str.Length; i++)
{
if (str[i] != ' ')
temp += str[i];
}
Console.WriteLine("Output from RemoveSpaces: {0}", temp);
return temp;
}
}
Outputs:
Output from RemoveSpaces: Thisisasamplestring
Output from ReverseString: gnirts elpmas a si sihT

Counting number of words in C#

I'm trying to count the number of words from a rich textbox in C# the code that I have below only works if it is a single line. How do I do this without relying on regex or any other special functions.
string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";
foreach(string av in split_text)
{
if (av == "")
{
space_count++;
}
else
{
new_text = new_text + av + ",";
}
}
new_text = new_text.TrimEnd(',');
split_text = new_text.Split(',');
MessageBox.Show(split_text.Length.ToString ());
char[] delimiters = new char[] {' ', '\r', '\n' };
whole_text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries).Length;
Since you are only interested in word count, and you don't care about individual words, String.Split could be avoided. String.Split is handy, but it unnecessarily generates a (potentially) large number of String objects, which in turn creates an unnecessary burden on the garbage collector. For each word in your text, a new String object needs to be instantiated, and then soon collected since you are not using it.
For a homework assignment, this may not matter, but if your text box contents change often and you do this calculation inside an event handler, it may be wiser to simply iterate through characters manually. If you really want to use String.Split, then go for a simpler version like Yonix recommended.
Otherwise, use an algorithm similar to this:
int wordCount = 0, index = 0;
// skip whitespace until first word
while (index < text.Length && char.IsWhiteSpace(text[index]))
index++;
while (index < text.Length)
{
// check if current char is part of a word
while (index < text.Length && !char.IsWhiteSpace(text[index]))
index++;
wordCount++;
// skip whitespace until next word
while (index < text.Length && char.IsWhiteSpace(text[index]))
index++;
}
This code should work better with cases where you have multiple spaces between each word, you can test the code online.
There are some better ways to do this, but in keeping with what you've got, try the following:
string whole_text = richTextBox1.Text;
string trimmed_text = whole_text.Trim();
// new line split here
string[] lines = trimmed_text.Split(Environment.NewLine.ToCharArray());
// don't need this here now...
//string[] split_text = trimmed_text.Split(' ');
int space_count = 0;
string new_text = "";
Now make two foreach loops. One for each line and one for counting words within the lines.
foreach (string line in lines)
{
// Modify the inner foreach to do the split on ' ' here
// instead of split_text
foreach (string av in line.Split(' '))
{
if (av == "")
{
space_count++;
}
else
{
new_text = new_text + av + ",";
}
}
}
new_text = new_text.TrimEnd(',');
// use lines here instead of split_text
lines = new_text.Split(',');
MessageBox.Show(lines.Length.ToString());
}
This was a phone screening interview question that I just took (by a large company located in CA who sells all kinds of devices that starts with a letter "i"), and I think I franked... after I got offline, I wrote this. I wish I were able to do it during interview..
static void Main(string[] args)
{
Debug.Assert(CountWords("Hello world") == 2);
Debug.Assert(CountWords(" Hello world") == 2);
Debug.Assert(CountWords("Hello world ") == 2);
Debug.Assert(CountWords("Hello world") == 2);
}
public static int CountWords(string test)
{
int count = 0;
bool wasInWord = false;
bool inWord = false;
for (int i = 0; i < test.Length; i++)
{
if (inWord)
{
wasInWord = true;
}
if (Char.IsWhiteSpace(test[i]))
{
if (wasInWord)
{
count++;
wasInWord = false;
}
inWord = false;
}
else
{
inWord = true;
}
}
// Check to see if we got out with seeing a word
if (wasInWord)
{
count++;
}
return count;
}
Have a look at the Lines property mentioned in #Jay Riggs comment, along with this overload of String.Split to make the code much simpler. Then the simplest approach would be to loop over each line in the Lines property, call String.Split on it, and add the length of the array it returns to a running count.
EDIT: Also, is there any reason you're using a RichTextBox instead of a TextBox with Multiline set to True?
I use an extension method for grabbing word count in a string. Do note, however, that double spaces will mess the count up.
public static int CountWords(this string line)
{
var wordCount = 0;
for (var i = 0; i < line.Length; i++)
if (line[i] == ' ' || i == line.Length - 1)
wordCount++;
return wordCount;
}
}
Your approach is on the right path. I would do something like, passing the text property of richTextBox1 into the method. This however won't be accurate if your rich textbox is formatting HTML, so you'll need to strip out any HTML tags prior to running the word count:
public static int CountWords(string s)
{
int c = 0;
for (int i = 1; i < s.Length; i++)
{
if (char.IsWhiteSpace(s[i - 1]) == true)
{
if (char.IsLetterOrDigit(s[i]) == true ||
char.IsPunctuation(s[i]))
{
c++;
}
}
}
if (s.Length > 2)
{
c++;
}
return c;
}
We used an adapted form of Yoshi's answer, where we fixed the bug where it would not count the last word in a string if there was no white-space after it:
public static int CountWords(string test)
{
int count = 0;
bool inWord = false;
foreach (char t in test)
{
if (char.IsWhiteSpace(t))
{
inWord = false;
}
else
{
if (!inWord) count++;
inWord = true;
}
}
return count;
}
using System.Collections;
using System;
class Program{
public static void Main(string[] args){
//Enter the value of n
int n = Convert.ToInt32(Console.ReadLine());
string[] s = new string[n];
ArrayList arr = new ArrayList();
//enter the elements
for(int i=0;i<n;i++){
s[i] = Console.ReadLine();
}
string str = "";
//Filter out duplicate values and store in arr
foreach(string i in s){
if(str.Contains(i)){
}else{
arr.Add(i);
}
str += i;
}
//Count the string with arr and s variables
foreach(string i in arr){
int count = 0;
foreach(string j in s){
if(i.Equals(j)){
count++;
}
}
Console.WriteLine(i+" - "+count);
}
}
}
int wordCount = 0;
bool previousLetterWasWhiteSpace = false;
foreach (char letter in keyword)
{
if (char.IsWhiteSpace(letter))
{
previousLetterWasWhiteSpace = true;
}
else
{
if (previousLetterWasWhiteSpace)
{
previousLetterWasWhiteSpace = false;
wordCount++;
}
}
}
public static int WordCount(string str)
{
int num=0;
bool wasInaWord=true;;
if (string.IsNullOrEmpty(str))
{
return num;
}
for (int i=0;i< str.Length;i++)
{
if (i!=0)
{
if (str[i]==' ' && str[i-1]!=' ')
{
num++;
wasInaWord=false;
}
}
if (str[i]!=' ')
{
wasInaWord=true;
}
}
if (wasInaWord)
{
num++;
}
return num;
}
class Program
{
static void Main(string[] args)
{
string str;
int i, wrd, l;
StringBuilder sb = new StringBuilder();
Console.Write("\n\nCount the total number of words in a string
:\n");
Console.Write("---------------------------------------------------
---\n");
Console.Write("Input the string : ");
str = Console.ReadLine();
l = 0;
wrd = 1;
foreach (var a in str)
{
sb.Append(a);
if (str[l] == ' ' || str[l] == '\n' || str[l] == '\t')
{
wrd++;
}
l++;
}
Console.WriteLine(sb.Replace(' ', '\n'));
Console.Write("Total number of words in the string is : {0}\n",
wrd);
Console.ReadLine();
}
This should work
input.Split(' ').ToList().Count;
This can show you the number of words in a line
string line = Console.ReadLine();
string[] word = line.Split(' ');
Console.WriteLine("Words " + word.Length);
You can also do it in this way!! Add this method to your extension methods.
public static int WordsCount(this string str)
{
return Regex.Matches(str, #"((\w+(\s?)))").Count;
}
And call it like this.
string someString = "Let me show how I do it!";
int wc = someString.WordsCount();

How can you remove duplicate characters in a string?

I have to implements a function that takes a string as an input and finds the non-duplicate character from this string.
So an an example is if I pass string str = "DHCD" it will return "DHC"
or str2 = "KLKLHHMO" it will return "KLHMO"
A Linq approach:
public static string RemoveDuplicates(string input)
{
return new string(input.ToCharArray().Distinct().ToArray());
}
It will do the job
string removedupes(string s)
{
string newString = string.Empty;
List<char> found = new List<char>();
foreach(char c in s)
{
if(found.Contains(c))
continue;
newString+=c.ToString();
found.Add(c);
}
return newString;
}
I should note this is criminally inefficient.
I think I was delirious on first revision.
For arbitrary length strings of byte-sized characters (not for wide characters or other encodings), I would use a lookup table, one bit per character (32 bytes for a 256-bit table). Loop through your string, only output characters that don't have their bits turned on, then turn the bit on for that character.
string removedupes(string s)
{
string t;
byte[] found = new byte[256];
foreach(char c in s)
{
if(!found[c]) {
t.Append(c);
found[c]=1;
}
}
return t;
}
I am not good with C#, so I don't know the right way to use a bitfield instead of a byte array.
If you know that your strings are going to be very short, then other approaches would offer better memory usage and/or speed.
void removeDuplicate()
{
string value1 = RemoveDuplicateChars("Devarajan");
}
static string RemoveDuplicateChars(string key)
{
string result = "";
foreach (char value in key)
if (result.IndexOf(value) == -1)
result += value;
return result;
}
It sounds like homework to me, so I'm just going to describe at a high level.
Loop over the string, examining each character
Check if you've seen the character before
if you have, remove it from the string
if you haven't, note that you've now seen that character
this is in C#. validation left out for brevity. primitive solution for removing duplicate chars from a given string
public static char[] RemoveDup(string s)
{
char[] chars = new char[s.Length];
int unique = 0;
chars[unique] = s[0]; // Assume: First char is unique
for (int i = 1; i < s.Length; i++)
{
// add char in i index to unique array
// if char in i-1 != i index
// i.e s = "ab" -> a != b
if (s[i-1] != s[i]
chars[++unique] = s[i];
}
return chars;
}
My answer in java language.
Posting here so that you might get a idea even it is in Java language.Algorithm would remain same.
public String removeDup(String s)
{
if(s==null) return null;
int l = s.length();
//if length is less than 2 return string
if(l<2)return s;
char arr[] = s.toCharArray();
for(int i=0;i<l;i++)
{
int j =i+1; //index to check with ith index
int t = i+1; //index of first repetative char.
while(j<l)
{
if(arr[j]==arr[i])
{
j++;
}
else
{
arr[t]=arr[j];
t++;
j++;
}
}
l=t;
}
return new String(arr,0,l);
}
you may use HashSet:
static void Main()
{
string textWithDuplicates = "aaabbcccggg";
Console.WriteLine(textWithDuplicates.Count());
var letters = new HashSet<char>(textWithDuplicates);
Console.WriteLine(letters.Count());
foreach (char c in letters) Console.Write(c);
}
class Program
{
static void Main(string[] args)
{
bool[] doesExists = new bool[256];
String st = Console.ReadLine();
StringBuilder sb = new StringBuilder();
foreach (char ch in st)
{
if (!doesExists[ch])
{
sb.Append(ch);
doesExists[ch] = true;
}
}
Console.WriteLine(sb.ToString());
}
}
Revised version of the first answer i.e: You don't need ToCharArray() function for this to work.
public static string RemoveDuplicates(string input)
{
return new string(input.Distinct().ToArray());
}
char *remove_duplicates(char *str)
{
char *str1, *str2;
if(!str)
return str;
str1 = str2 = str;
while(*str2)
{
if(strchr(str, *str2)<str2)
{
str2++;
continue;
}
*str1++ = *str2++;
}
*str1 = '\0';
return str;
}
char* removeDups(const char* str)
{
char* new_str = (char*)malloc(256*sizeof(char));
int i,j,current_pos = 0,len_of_new_str;
new_str[0]='\0';
for(i=0;i<strlen(str);i++)
{
len_of_new_str = strlen(new_str);
for(j=0;j<len_of_new_str && new_str[j]!=str[i];j++)
;
if(j==len_of_new_str)
{
new_str[len_of_new_str] = str[i];
new_str[len_of_new_str+1] = '\0';
}
}
return new_str;
}
Hope this helps
String str="AABBCANCDE";
String newStr="";
for( int i=0; i<str.length(); i++)
{
if(!newStr.contains(str.charAt(i)+""))
newStr= newStr+str.charAt(i);
}
System.out.println(newStr);
// Remove both upper-lower duplicates
public static string RemoveDuplicates(string key)
{
string Result = string.Empty;
foreach (char a in key)
{
if (Result.Contains(a.ToString().ToUpper()) || Result.Contains(a.ToString().ToLower()))
continue;
Result += a.ToString();
}
return Result;
}
var input1 = Console.ReadLine().ToLower().ToCharArray();
var input2 = input1;
var WithoutDuplicate = input1.Union(input2);
Console.WriteLine("Enter String");
string str = Console.ReadLine();
string result = "";
result += str[0]; // first character of string
for (int i = 1; i < str.Length; i++)
{
if (str[i - 1] != str[i])
result += str[i];
}
Console.WriteLine(result);
I like Quintin Robinson answer, only there should be some improvements like removing List, because it is not necessarry in this case.
Also, in my opinion Uppercase char ("K") and lowercase char ("k") is the same thing, so they should be counted as one.
So here is how I would do it:
private static string RemoveDuplicates(string textEntered)
{
string newString = string.Empty;
foreach (var c in textEntered)
{
if (newString.Contains(char.ToLower(c)) || newString.Contains(char.ToUpper(c)))
{
continue;
}
newString += c.ToString();
}
return newString;
}
Not sure how optimal it is:
public static string RemoveDuplicates(string input)
{
var output = string.Join("", input.ToHashSet());
return output;
}
Below is the code to remove duplicate chars from a string
var input = "SaaSingeshe";
var filteredString = new StringBuilder();
foreach(char c in input)
{
if(filteredString.ToString().IndexOf(c)==-1)
{
filteredString.Append(c);
}
}
Console.WriteLine(filteredString);
Console.ReadKey();
namespace Demo { class Program {
static void Main(string[] args) {
string myStr = "kkllmmnnouo";
Console.WriteLine("Initial String: "+myStr);
// var unique = new HashSet<char>(myStr);
HashSet<char> unique = new HashSet<char>(myStr);
Console.Write("New String after removing duplicates: ");
foreach (char c in unique)
Console.Write(c);
} } }
this works for me
private string removeDuplicateChars(String value)
{
return new string(value.Distinct().ToArray());
}

Categories