I am really a beginner, I already know
string.indexOf("");
Can search for a whole word, but when I tried to search for e.g: ig out of pig, it doesn't work.
I have a similar string here(part of):
<Special!>The moon is crashing to the Earth!</Special!>
Because I have a lot of these in my file and I just cannot edited all of them and add a space like:
< Special! > The moon is crashing to the Earth! </ Special! >
I need to get the sub-string of Special! and The moon is crashing to the Earth!
What is the simple way to search for a part of a word without adding plugins like HTMLAgilityPack?
IndexOf will work, you are probably just using it improperly.
If your string is in a variable call mystring you would say mystring.IndexOf and then pass in the string you are looking for.
string mystring = "somestring";
int position = mystring.IndexOf("st");
How are you using it? You should use like this:
string test = "pig";
int result = test.IndexOf("ig");
// result = 1
If you want to make it case insensitive use
string test = "PIG";
int result = test.IndexOf("ig", StringComparison.InvariantCultureIgnoreCase);
// result = 1
String.IndexOf Method - MSDN
Please try this:
string s = "<Special!>The moon is crashing to the Earth!</Special!>";
int whereMyStringStarts = s.IndexOf("moon is crashing");
IndexOf should work with spaces too, but maybe you have new line or tab characters, not spaces?
Sometimes case-sensitivity is important. You may control it by additional parameter called comparisonType. Example:
int whereMyStringStarts = s.IndexOf("Special", StringComparison.OrdinalIgnoreCase);
More information about IndexOf: String.IndexOf Method at MSDN
Anyway, I think you may need regular expressions to create better parser. IndexOf is very primitive method and you may stuck in big mess of code.
string page = "<Special!>The moon is crashing to the Earth!</Special!>";
if (page.Contains("</Special!>"))
{
pos = page.IndexOf("<Special!>");
propertyAddress = page.Substring(10, page.IndexOf("</Special!>")-11);
//i used 10 because <special!> is 10 chars, i used 11 because </special!> is 11
}
This will give you "the moon is crashing to the earth!"
Related
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}
I learn c# and I have a question about strings. There is a string with full of '1's and '0's. But I don't know its length. I get the length of string with while loop. But if length is less than 8, I need to complete its length to 8 with '0's. I tried to declare a new string with 7 '0's. And did this: (where a is my string and zeroAdd is the '0's I want to add.
if(length<8)
{
for(i=length;i<8;i++)
a[i]=zeroAdd[8-length];
a[i]='\0';
}
but it didn't work. I can't use the shortcuts I saw on the internet and wanted to ask you. I would appreciate if you could explain it to me like this. Thanks in advance. Have a good one.
Why not use the inbuilt padding?
string myString = "1101";
var result = myString.PadLeft(8,'0');
Gives you:
00001101
To do it with a loop (and right-padding), you can do this:
string myString = "1101";
while (myString.Length < 8)
myString += "0";
I can't seem to find a good solution to this issue. I've got an array of strings that are fed in from a report that I recieve about lost or stolen equipment. I've been using the string.IndexOf function through the rest of the form and it works quite well. This issue is with the field that says if the device was lost or stolen.
Example:
"Lost or Stolen? Lost"
"Lost or Stolen? Stolen"
I need to be able to read this but when I do string.IndexOf(#"Lost") it will always return lost because it's in the question.
Unfortunately I'm not able to change the form itself in any way and due to the nature of how it's submited I can't just write code the knocks the first 15 or so characters off the string because that may be too few in some cases.
I would really like something in C# that would allow me to continue to search a string after the first result is found so that the logic would look like:
string my_string = "Lost or Stolen? Stolen";
searchFor(#"Stolen" in my_string)
{
Found Stolen;
Does it have "or " infront of it? yes;
ignore and keep searching;
Found Stolen again;
return "Equipment stolen";
}
Couple of options here. You could look for the last index of a space and take the rest of the string:
string input = "Lost or Stolen? Stolen";
int lastSpaceIndex = input.LastIndexOf(' ');
string result = input.Substring(lastSpaceIndex + 1);
Console.WriteLine(result);
Or you could split it and take the last word:
string input = "Lost or Stolen? Lost";
string result = input.Split(' ').Last();
Console.WriteLine(result);
Regex is also an option, but overkill given the simpler solutions above. A nice shortcut that fits this scenario is to use the RegexOptions.RightToLeft option to get the first match starting from the right:
string result = Regex.Match(input, #"\w+", RegexOptions.RightToLeft).Value;
If I understand your requirement, you're looking for an instance of Lost or Stolen after a ?:
var q = myString.IndexOf("?");
var lost = q >= 0 && myString.IndexOf("Lost", q) > 0;
var stolen = q >= 0 && myString.IndexOf("Stolen", q) > 0;
// or
var lost = myString.LastIndexOf("Lost") > myString.IndexOf("?");
var stolen = myString.LastIndexOf("Stolen") > myString.IndexOf("?");
// don't forget
var neither = !lost && !stolen;
You can look for the string 'Lost' and if it occurs twice, then you can confirm it is 'Lost'.
Its possible in this case that you could use index of on a substring knowing that it is always going to say lost or stolen first
so you parse out the lost or stolen, then like for you keyword to match the remaining string.
something like:
int questionIndex = inputValue.indexOf("?");
string toMatch = inputValue.Substring(questionIndex);
if(toMatch == "Lost")
If it works for your use case, it might be easier to use .EndsWith().
bool lost = my_string.EndsWith("Lost");
My strings look like that: aaa/b/cc/dd/ee . I want to cut first part without a / . How can i do it? I have many strings and they don't have the same length. I tried to use Substring(), but what about / ?
I want to add 'aaa' to the first treeNode, 'b' to the second etc. I know how to add something to treeview, but i don't know how can i receive this parts.
Maybe the Split() method is what you're after?
string value = "aaa/b/cc/dd/ee";
string[] collection = value.Split('/');
Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a String array.
Based on your updates related to a TreeView (ASP.Net? WinForms?) you can do this:
foreach(string text in collection)
{
TreeNode node = new TreeNode(text);
myTreeView.Nodes.Add(node);
}
Use Substring and IndexOf to find the location of the first /
To get the first part:
// from memory, need to test :)
string output = String.Substring(inputString, 0, inputString.IndexOf("/"));
To just cut the first part:
// from memory, need to test :)
string output = String.Substring(inputString,
inputString.IndexOf("/"),
inputString.Length - inputString.IndexOf("/");
You would probably want to do:
string[] parts = "aaa/b/cc/dd/ee".Split(new char[] { '/' });
Sounds like this is a job for... Regular Expressions!
One way to do it is by using string.Split to split your string into an array, and then string.Join to make whatever parts of the array you want into a new string.
For example:
var parts = input.Split('/');
var processedInput = string.Join("/", parts.Skip(1));
This is a general approach. If you only need to do very specific processing, you can be more efficient with string.IndexOf, for example:
var processedInput = input.Substring(input.IndexOf('/') + 1);
I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: Remove All Text After Certain Point).
I've got the following code:
[Test]
public void stringManipulation()
{
String filename = "testpage.aspx";
String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);
String expected = "http://localhost:2000/somefolder/myrep/";
String actual = urlWithoutPageName;
Assert.AreEqual(expected, actual);
}
I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.
How can I get the remove the query string from the full URL such that this test passes?
For string manipulation, if you just want to kill everything after the ?, you can do this
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
input = input.Substring(0, index);
Edit: If everything after the last slash, do something like
string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
input = input.Substring(0, index); // or index + 1 to keep slash
Alternately, since you're working with a URL, you can do something with it like this code
System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Here's another simple solution. The following code will return everything before the '|' character:
if (path.Contains('|'))
path = path.Split('|')[0];
In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':
if (path.Contains('|'))
path = path.Split('|')[1];
(All I changed in the second piece of code was the index of the array.)
The Uri class is generally your best bet for manipulating Urls.
To remove everything before a specific char, use below.
string1 = string1.Substring(string1.IndexOf('$') + 1);
What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!
But for a URL, I would use the built in .NET class to take of that.
Request.QueryString helps you to get the parameters and values included within the URL
example
string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();
so the customername variable should be equal to dave
regards
I second Hightechrider: there is a specialized Url class already built for you.
I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.
you can use .NET's built in method to remove the QueryString.
i.e., Request.QueryString.Remove["whatever"];
here whatever in the [ ] is name of the querystring which you want to
remove.
Try this...
I hope this will help.
You can use this extension method to remove query parameters (everything after the ?) in a string
public static string RemoveQueryParameters(this string str)
{
int index = str.IndexOf("?");
return index >= 0 ? str.Substring(0, index) : str;
}