Find and replace 100 in a string - c#

I have a string that could be anything like
100100001
or
101000
I need to find a way to remove the 100 until it's reduced to it's simplest form
100100001 ==> 001
101000 ==> empty
Can't use 3rd party tools
must only use

System
System.Collections.Generic
System.IO

You can do it with a simple loop, checking if the string contains the value an if it does, replace it with blank:
var input = "101000";
while(input.Contains("100"))
{
input = input.Replace("100", "");
}

You could also use recursion, something like this:
public string Reduce(string s)
{
return s.Contains("100") ? Reduce(s.Replace("100", string.Empty)) : s;
}

Related

How Get everything after index of a specific character to end?

I'm trying to get some part of string by substring and this is my string :{"samanState":"OK","samanResNum":"97d590e2-9ce3-49f9-85cf-2228b33cad57","samanTraceNo":"479936"} I can't do something like this : substring(8,16) because this string is change every time. I want to get 479936 from that. I'm sure TraceNo":" is static and never change so I did this :
<td>#(bankDepositHistoryItem.AdditionalData.Substring
(bankDepositHistoryItem.AdditionalData.IndexOf("TraceNo\":\""),
bankDepositHistoryItem.AdditionalData.Length- bankDepositHistoryItem.AdditionalData.IndexOf("TraceNo\":\"")-2)) </td>
but the out put is : TraceNo":"479936 How should I get this : 479936
I have to say that I Know this is possible with serialize and deserialize but I want to know if this is possible with substring or split or methods like these.
Many thanks
That is a JSON string, so I would first convert the string to a .NET object using the popular Json.NET framework library.
After adding the Newtonsoft.Json NuGet package to your project, your code would look something like this:
#using Newtonsoft.Json.Linq //add this to your Razor page or to _ViewImports.cshtml
<td>#(JObject.Parse(bankDepositHistoryItem)["samanTraceNo"])</td>
If you still want to parse the string, you can use a couple of handy string extension methods (I have variations for integers and Regex as well):
public static string Past(this string s, string starter) {
var starterPos = s.IndexOf(starter);
return starterPos == -1 ? String.Empty : s.Substring(starterPos + starter.Length);
}
public static string UpTo(this string s, string stopper) {
var stopPos = s.IndexOf(stopper);
return (stopPos >= 0) ? s.Substring(0, stopPos) : s;
}
Then extract with:
var ans = bankDepositHistoryItem.Past("\"samanTraceNo\":\"").UpTo("\"");

Verify empty field Selenium C#

I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
Console.WriteLine("This field can not be empty");
}
Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?
Thank you in advance!
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.
For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.
This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.
For Empty / White space / Null, use following APIs of the string class
string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)
For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits
string pattern = #"^\d{20}$";
var booleanResult = Regex.Match(value,pattern).Success
I'm not sure that this way will work in your case. Code:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text or firstName.getAttribute("value");. When u will have this you will able to check
:
var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}

C# - Merging strings from a certain position

I want to create a function but I don't know how it would work or how to create it. I want to create a function something similar to below.
I have a string, lets say its this for example:
string myString = "This is my string and it will forever be my string.";
What if I wanted to split this by a space and get each part? which I do...
string[] parts = myString.Split(' ');
Now, I want to get everything but the first 3 words in my string parts, how would I merge each string in parts except the first 3? which will return
string and it will forever be my string.
Something similar to this:
public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{
}
public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{
return String.Join(" ", parts.Skip(start));
}
Quick explanation of the code:
string.Join(separator, IEnumerable values)
This joins an IEnumerable object containing strings to one, unified string.
Docs: https://msdn.microsoft.com/en-us/library/system.string.join(v=vs.110).aspx
parts.Skip(int count)
This part of the code skips a given amount of elements, before returning them.
Skip(int count) is an extension method found in the System.Linq namespace.
You need .Net 3.5 or higher in order for you to be able to use this method.
Docs: https://msdn.microsoft.com/en-us/library/bb358985(v=vs.110).aspx
string myString = "This is my string and it will forever be my string.";
string[] words = myString.Split(' ');
var myNewString = string.Join(" ", words.Skip(3));

words stemmer class c#

I am trying the following stemming class :
static class StemmerSteps
{
public static string stepSufixremover(this string str, string suffex)
{
if (str.EndsWith(suffex))
{
................
}
return str;
}
public static string stepPrefixemover(this string str, string prefix)
{
if (str.StartsWith(prefix)
{
.....................
}
return str;
}
}
this class works with one prefix or suffix. is there any suggestion to allow a list of prefixes or suffixes to go through the class and compare against each (str). your kind action really appreciated.
Instead of creating your own class from scratch (unless this is homework) I would definitive use an existing library. This answer provides an example of code that that implements the Porter Stemming Algorithm:
https://stackoverflow.com/questions/7611455/how-to-perform-stemming-in-c
Put your suffix/prefixes in a collection (like a List<>), and loop through and apply each possible one. This collection would need to be passed into the method.
List<string> suffixes = ...;
for (suffix in suffixes)
if (str.EndsWith(suffix))
str = str.Remove(str.Length - suffix.Length, suffix.Length);
EDIT
Considering your comment:
"just want to look if the string starts-/endswith any of the passed strings"
may be something like this can fit your needs:
public static string stepSufixremover(this string str, IEnumerable<string> suffex)
{
string suf = suffex.Where(x=>str.EndsWith(x)).SingleOrDefault();
if(!string.IsNullOrEmpty(suf))
{
str = str.Remove(str.Length - suf.Length, suf.Length);
}
return str;
}
If you use this like:
"hello".stepone(new string[]{"lo","l"}).Dump();
it produces:
hel
The simplest code would involve regular expressions.
For example, this would identify some English suffixes:
'^(.*?)(ing|ly|ed|ious|ies|ive|es|s|ment)?$'
One problem is that stemming is not as accurate as lemmatization. Lematization would require POS tagging for accuracy. For example, you don't want to add an -ing suffix to dove if it's a noun.
Another problem is that some suffixes also require prefixes. For example, you must add en- to -rich- to add a -ment suffix in en-rich-ment -- unlike a root like -govern- where you can add the suffix without any prefix.

Check for special characters (/*-+_#&$#%) in a string?

How do I check a string to make sure it contains numbers, letters, or space only?
In C# this is simple:
private bool HasSpecialChars(string yourString)
{
return yourString.Any(ch => ! char.IsLetterOrDigit(ch));
}
The easiest way it to use a regular expression:
Regular Expression for alphanumeric and underscores
Using regular expressions in .net:
http://www.regular-expressions.info/dotnet.html
MSDN Regular Expression
Regex.IsMatch
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
if(regexItem.IsMatch(YOUR_STRING)){..}
string s = #"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c)
|| Char.IsWhiteSpace(c)).ToArray());
if (s != withoutSpecial)
{
Console.WriteLine("String contains special chars");
}
Try this way.
public static bool hasSpecialChar(string input)
{
string specialChar = #"\|!#$%&/()=?»«#£§€{}.-;'<>_,";
foreach (var item in specialChar)
{
if (input.Contains(item)) return true;
}
return false;
}
String test_string = "tesintg#$234524##";
if (System.Text.RegularExpressions.Regex.IsMatch(test_string, "^[a-zA-Z0-9\x20]+$"))
{
// Good-to-go
}
An example can be found here: http://ideone.com/B1HxA
If the list of acceptable characters is pretty small, you can use a regular expression like this:
Regex.IsMatch(items, "[a-z0-9 ]+", RegexOptions.IgnoreCase);
The regular expression used here looks for any character from a-z and 0-9 including a space (what's inside the square brackets []), that there is one or more of these characters (the + sign--you can use a * for 0 or more). The final option tells the regex parser to ignore case.
This will fail on anything that is not a letter, number, or space. To add more characters to the blessed list, add it inside the square brackets.
Use the regular Expression below in to validate a string to make sure it contains numbers, letters, or space only:
[a-zA-Z0-9 ]
You could do it with a bool. I've been learning recently and found I could do it this way. In this example, I'm checking a user's input to the console:
using System;
using System.Linq;
namespace CheckStringContent
{
class Program
{
static void Main(string[] args)
{
//Get a password to check
Console.WriteLine("Please input a Password: ");
string userPassword = Console.ReadLine();
//Check the string
bool symbolCheck = userPassword.Any(p => !char.IsLetterOrDigit(p));
//Write results to console
Console.WriteLine($"Symbols are present: {symbolCheck}");
}
}
}
This returns 'True' if special chars (symbolCheck) are present in the string, and 'False' if not present.
A great way using C# and Linq here:
public static bool HasSpecialCharacter(this string s)
{
foreach (var c in s)
{
if(!char.IsLetterOrDigit(c))
{
return true;
}
}
return false;
}
And access it like this:
myString.HasSpecialCharacter();
private bool isMatch(string strValue,string specialChars)
{
return specialChars.Where(x => strValue.Contains(x)).Any();
}
Create a method and call it hasSpecialChar with one parameter
and use foreach to check every single character in the textbox, add as many characters as you want in the array, in my case i just used ) and ( to prevent sql injection .
public void hasSpecialChar(string input)
{
char[] specialChar = {'(',')'};
foreach (char item in specialChar)
{
if (input.Contains(item)) MessageBox.Show("it contains");
}
}
in your button click evenement or you click btn double time like that :
private void button1_Click(object sender, EventArgs e)
{
hasSpecialChar(textbox1.Text);
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the [https://www.nuget.org/packages/Extensions.cs][1] package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Based on #prmph's answer, it can be even more simplified (omitting the variable, using overload resolution):
yourString.Any(char.IsLetterOrDigit);
No special characters or empty string except hyphen
^[a-zA-Z0-9-]+$

Categories

Resources