Why my string.Remove() is not working as expected? [duplicate] - c#

This question already has an answer here:
string.Remove doesnt work [duplicate]
(1 answer)
Closed 6 years ago.
I am trying to solve this problem of finding if two words are anagrams of one another (if we rearrange a string, it matches second string).
Based on Remove single character from a string I built my own function:
public class AreAnagrams
{
public static bool AreStringsAnagrams(string FirstString, string SecondString)
{
if (FirstString == null || b == null)
return false;
if (FirstString.Length != SecondString.Length)
return false;
for (int i = 0; i < SecondString.Length; i++)
{
if (FirstString.IndexOf(SecondString[i]) == -1)
return false;
else
FirstString.Remove(FirstString.IndexOf(SecondString[i]), 1); // Here it does not modify FirstString, even if I put 2nd parameter as 1
}
if (FirstString.Length > 0)
return false;
return true;
}
public static void Main(string[] args)
{
Console.WriteLine(AreStringsAnagrams("neural", "unreal"));
}
}
On my watch I see FirstString still as is. What is the problem? Please and thank you

Assign the result to FirstString
FirstString = FirstString.Remove(FirstString.IndexOf(SecondString[i]), 1);

Related

C# Palindrome Test [duplicate]

This question already has answers here:
Check if a string is a palindrome
(33 answers)
Closed 3 years ago.
I need to create a IsPalindrome function where it will determine if a provided string is a palindrome. Alphanumeric chars will be considered when evaluating whether or not the string is a palindrome. With this said, I am having trouble trying to disreguard the spaces and the Caps. Here is what my function looks like now.
If this makes a difference: After this function is done I will then have to have parse a JSON file and have each element in the "strings" array, into the IsPalindrome function.
Any tips?
private static bool IsPalindrome(string value)
{
var min = 0;
var max = value.Length - 1;
while (true)
{
if (min > max)
return true;
var a = value[min];
var b = value[max];
if (if (char.ToLower(a) == char.ToLower(b))
{
return true;
}
else {
return false;
}
min++;
max--;
}
The way I'd do this is to turn the string into an array of characters, skipping non-letter characters, and making all the characters lowercase. Then, I'd use an index to check if the first half of the array is equal to the last. Something like this:
public static bool IsPalindrome(string value)
{
char[] forwards = (from c in value.ToLower().ToCharArray() where char.IsLetter(c) select c).ToArray();
int middle = (forwards.Length / 2) + 1;
for (int i = 0; i < middle; i++)
if (forwards[i] != forwards[forwards.Length - 1 - i])
return false;
return true;
}
That first line uses LINQ to make the array, so you need a using System.Linq;

How to check if a string ends with a number, without regex? [duplicate]

This question already has answers here:
Extract number at end of string in C#
(9 answers)
Regex for number at the end of string?
(5 answers)
Closed 3 years ago.
I need to check if the last character of a string ends with an int. I would like to avoid using a regular expression, because I think it is very hard, but if there is no smoother way of doing it, I will try it.
I basically tried something that looks like this:
text.EndsWith(INTEGER)]
Boolean result = char.IsDigit(text[text.Length - 1]);
using linq Last method and Isdigit function
bool isDigit = Char.IsDigit(("one1").Last());
Isolate the last character and try parse it to integer:
private static bool IsStringEndsWithDigit(string str)
{
if (String.IsNullOrEmpty(str))
{
return false;
// or throw an exception
// throw new Exception("string can not be empty");
}
string last = str.Substring(str.Length - 1, 1);
int num;
var isNum = int.TryParse(last, out num);
return isNum;
}
var lastChar = text.Last();
var endsWithNum = lastChar >= '0' && lastChar <= '9';
string s = "hello world0";
int len = s.Length;
List<char> digits = new List<char>(){'0','1','2','3','4','5','6','7','8','9'};
if (digits.Contains(s[len - 1]))
{
Console.WriteLine("last character is digits");
}

how to refactor code to return IsPalindrome

using a mock c# question on https://www.testdome.com/t
I have coded
using System;
public class Palindrome
{
public static bool IsPalindrome(string word)
{
string testWord = word;
string first = word[0].ToString();
string last = word[word.Length - 1].ToString();
bool isPal = false;
while (testWord.Length > 1)
{
Console.WriteLine(testWord);
if (first.ToLower() == last.ToLower())
{
testWord = testWord.Remove(0,1);
testWord = testWord.Remove(testWord.Length - 1);
isPal = true;
}
}
return isPal;
}
public static void Main(string[] args)
{
Console.WriteLine(Palindrome.IsPalindrome("Deleveled"));
}
}
this code is working but it is failing me on
lowercase words: time limit exceeded
various words: time limit exceeded.
What changes could I make to refactor the code to work faster?
No need to write multiple line of code, you can check Palindrome in one line,
Magic of Linq,
bool isPalindrome = str.SequenceEqual(str.Reverse());
If you want to ignore case then convert original string and reverse string to lower case and then check its sequence
string str = "Madam";
var strReverse = str.ToLower().Reverse();
var isPalindrome = str.ToLower().SequenceEqual(strReverse);
Basically, Palindrome check is a check where actual string is equal to its reverse. When we check original string to reverse string that time we need not to travel till the end. We just need to check first letter with it's last and so on...
Here is non-Linq Palindrome check,
public static bool IsPalindrome(string word)
{
string testWord = word;
for(int i = 0; i < word.Length/2; i++)
{
if(char.ToLower(testWord[i]) != char.ToLower(testWord[testWord.Length - i - 1]))
return false;
}
return true;
}
POC : . net fiddle
One thing you can do is immediately return if you find a non-match.

Linear Search Using Text File C# [duplicate]

This question already has answers here:
Fastest way to find strings in a file
(5 answers)
Closed 5 years ago.
So I have a text file which I would like to search through for a number and if it is found then outputs a message number is found and if not then not found.
Currently I have read the text file into a string and asked the user what number they would like to search for. The part I am stuck on is the code for the linear search for a string. I want to look for a string because other files I will use may contain words.
Code So far:
public static void search() // Search for values
{
Console.WriteLine("Enter 1 to search through days");
int operation = Convert.ToInt32(Console.ReadLine());
if (operation == 1)
{
String[] myArray = File.ReadAllLines("Data1/Day_1.txt");
Console.WriteLine("Enter number to search");
String myString = Console.ReadLine();
}
}
I have seen some code for a linear search but not sure how to apply it properly to my example. I understand how it works but problem is with getting code in the correct order. Not too good at coding in c#. Any help would be much appreciated. Thanks
Generic Linear Search Code :
static int Search(string[] list, string elementSought)
{
bool found = false;
int max = list.Length - 1;
int currentElement = 0;
do
{
if (list[currentElement] == elementSought)
{
found = true;
}
else
{
currentElement = currentElement + 1;
}
} while (!(found == true || currentElement > max));
if (found == true)
{
return currentElement;
}
else
{
return -1;
}
}
Update:
public static void search() // Search for values
{
Console.WriteLine("1=Day 2=Depth");
int operation = Convert.ToInt32(Console.ReadLine());
if (operation == 1)
{
String[] myArray = File.ReadAllLines("Data1/Day_1.txt");
}
else if (operation == 2)
{
String[] myArray = File.ReadAllLines("Data1/Months_1.txt");
}
Console.WriteLine("Enter number to search");
String myString = Console.ReadLine();
int i = 0;
int j = 0;
var regex = new Regex(myString);
foreach (string array in myArray)
{
if (regex.IsMatch(array))
{
i++;
}
else if (regex.IsMatch(array))
{
j++;
}
}
if (i > 0)
{
Console.WriteLine("Found match! - {1} Appeared {0} time(s)",i,myString);
}
else if(j == 0)
{
Console.WriteLine("No Match for {0} in Data", myString);
}
Console.ReadLine();
}
How do I change it so that if I choose the second file that it selects that as the one to use as my Array?
You can use Array.IndexOf. It will return -1 if the item is not found int the array, otherwise the index of its first occurrence.
Example (console app)
static void Main(string[] args)
{
string[] list = {"xxx", "yyy", "aaa", "bbb"};
var found = Search(list, "gggg");
}
static bool Search(string[] list, string elementSought)
{
var index = Array.IndexOf(list, elementSought);
var found = index != -1;
return found;
}
you've overcomplicated the task at hand, simply use a for loop for a linear search or using Linq:
static int Search(string[] list, string elementSought)
{
return list.ToList().FindIndex(s => s == elementSought);
}
You need to loop through your array of strings in search of a match. Use a regex to check for a match.
Console.WriteLine("Enter number to search");
String myString = Console.ReadLine();
var regex = new Regex(myString);
foreach (string array in myArray)
if (regex.IsMatch(array))
Console.WriteLine("Found match!");

c# if String Contains 2 "hallo" [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How would you count occurences of a string within a string (C#)?
I want to check if a String contains 2 things..
String hello = "hellohelloaklsdhas";
if hello.Contains(*hello 2 Times*); -> True
How can I solve this?
You could use a regex :)
return Regex.Matches(hello, "hello").Count == 2;
This matches the string hello for the pattern "hello" and returns true if the count is 2.
Regular expressions.
if (Regex.IsMatch(hello,#"(.*hello.*){2,}"))
I guess you meant "hello", and this will match a string with at least 2 "hello" (not exactly 2 "hello")
public static class StringExtensions
{
public static int Matches(this string text, string pattern)
{
int count = 0, i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
}
class Program
{
static void Main()
{
string s1 = "Sam's first name is Sam.";
string s2 = "Dot Net Perls is about Dot Net";
string s3 = "No duplicates here";
string s4 = "aaaa";
Console.WriteLine(s1.Matches("Sam")); // 2
Console.WriteLine(s1.Matches("cool")); // 0
Console.WriteLine(s2.Matches("Dot")); // 2
Console.WriteLine(s2.Matches("Net")); // 2
Console.WriteLine(s3.Matches("here")); // 1
Console.WriteLine(s3.Matches(" ")); // 2
Console.WriteLine(s4.Matches("aa")); // 2
}
}
You can use a regex, and check the length of the result of Matches function. If it's two you win.
new Regex("hello.*hello").IsMatch(hello)
or
Regex.IsMatch(hello, "hello.*hello")
If you use a regular expression MatchCollection you can get this easily:
MatchCollection matches;
Regex reg = new Regex("hello");
matches = reg.Matches("hellohelloaklsdhas");
return (matches.Count == 2);
IndexOf
You can use the IndexOf method to get the index of a certain string. This method has an overload that accepts a starting point, from where to look. When the specified string is not found, -1 is returned.
Here is an example that should speak for itself.
var theString = "hello hello bye hello";
int index = -1;
int helloCount = 0;
while((index = theString.IndexOf("hello", index+1)) != -1)
{
helloCount++;
}
return helloCount==2;
Regex
Another way to get the count is to use Regex:
return (Regex.Matches(hello, "hello").Count == 2);
IndexOf:
int FirstIndex = str.IndexOf("hello");
int SecondIndex = str.IndexOf("hello", FirstIndex + 1);
if(FirstIndex != -1 && SecondIndex != -1)
{
//contains 2 or more hello
}
else
{
//contains not
}
or if you want exactly 2: if(FirstIndex != -1 && SecondIndex != -1 && str.IndexOf("hello", SecondIndex) == -1)

Categories

Resources