I am converting code from Java to C#, but having issues figuring out some keyword equivalence. I have looked over the web and can't find anything. Updated added number 3.
1) Does anyone know what C# uses for charAt()? Below is how I am trying to use it.
curr = tokens[i].charAt(0);
2) Also having issues converting isEmpty() to C# syntax.
if (par.isEmpty())
3) How should I convert this:
op2 = compute.pop().intValue();
Thanks!
1) Strings can have their characters accessed by using the [] operator:
curr = (tokens[i])[0];
2) IsEmpty becomes String.IsNullOrEmpty or String.IsNullOrWhiteSpace depending on what you want (the second is only available in .NET 4+ as well).
3) From what research I could find, it looks like intValue deals with boxing/unboxing. If you stick with working with ints, you shouldn't need to worry about that in C#. "Pop" will work the same if you have a Stack collection. Hopefully that gives you enough to convert the line.
1) In C# a string is also an array of characters.So you can access a character using the indexer:
curr = tokens[i][0]
2) You can compare your string with string.Empty or use String.IsNullOrEmpty method to check whether a string is empty or not:
if( par == string.Empty )
OR:
if( string.IsNullOrEmpty(par) );
Assuming tokens[i] is a string, treat the string as an array of characters:
var firstCharacter = tokens[i][0];
Assuming par is also a string, the string.IsNullOrEmpty() method can help you test whether or not a particular string is empty:
if (string.IsNullOrEmpty(par))
{
}
If par is a Stack<String> as you've indicated, then you could test whether it was empty (has no elements) with a simple bit of LINQ:
if (!par.Any())
{
// par has no elements
}
Alternatively, you could use the Count property in the Stack class:
if (par.Count == 0)
{
// par has no elements
}
A different approach:
1) You can use curr = tokens[i].ElementAt(0); This will return the same result as charAt(0)
2) if( string.IsNullOrEmpty(par) ); will do the job.
Related
This question already has answers here:
How can I check if a string exists in another string
(10 answers)
Closed 4 years ago.
Suppose,i have two strings.NameIs and Nam.Now i can check if one string is as same as the other using :
If (string1 == string2)
But it won't work here as the strings are not the same.But a portion of it is same.What i am trying to achieve is to check if my main string has any portion of the string given...I came across String.StartWith and EndWith methods but there,i need to specify what the string might start or end with but i cannot as the strings can be anything(that's why at the beginning,i said "Suppose").
So my first question is how to achieve this ? I don't want any step=to=step instruction but atleast a little bit of direction :)
However,if i get past that,there's still a drawback and it is the Case-Sensitive issue.I've come across this but i can't seem to figure the required implementation of this in my case because i need to overcome the first issue first.
How should i achieve these ?
For ordinal comparison you can use
str1.Contains(str2);
If you need your comparison to be case-insensitive you can do
str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) >= 0;
Note that you can hide the latter in an extension method, like
static bool ContainsIgnoreCase(this string #this, string other)
=> #this.IndexOf(other, StringComparison.OrdinalIgnoreCase) >= 0;
Use String.Contains
if (stringValue.ToLower().Contains(anotherString.ToLower())) {
// Do Work //
}
Just remember to check that strings aren't null when doing contains comparing, or you will get an ArgumentNullException..
To check if substring is contained in main string, and to ignore case-sensitivity do this, its a boolean function that takes two string parameters:
public bool DoesStringExistInsideMainString(string mainString, string subString)
{
return mainString.ToLower().Contains(subString.ToLower());
}
Easiest way is this:
a = a?.ToLowerInvariant();
b = b?.ToLowerInvariant();
if(a==null || b==null || a.Contains(b) || b.Contains(a))
{
//do stuff
}
Why null propogates into true? Because if any variable is null it will definitly contains in other variable. The other two specs is just for non-null entries.
Please note, the 'C#' tag was included intentionally, because I could accept C# syntax for my answer here, as I have the option of doing this both client-side and server-side. Read the 'Things You May Want To Know' section below. Also, the 'regex' tag was included because there is a strong possibility that the use of regular expressions is the best approach to this problem.
I have the following highlight Plug-In found here:
http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
And here is the code in that plug-in:
/*
highlight v4
Highlights arbitrary terms.
<http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html>
MIT license.
Johann Burkard
<http://johannburkard.de>
<mailto:jb#eaio.com>
*/
jQuery.fn.highlight = function(pat) {
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var pos = node.data.toUpperCase().indexOf(pat);
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(pat.length);
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
return this.length && pat && pat.length ? this.each(function() {
innerHighlight(this, pat.toUpperCase());
}) : this;
};
jQuery.fn.removeHighlight = function() {
return this.find("span.highlight").each(function() {
this.parentNode.firstChild.nodeName;
with (this.parentNode) {
replaceChild(this.firstChild, this);
normalize();
}
}).end();
};
This plug-in works pretty easily.
If I wanted to highlight all instances of the word "Farm" within the following element...(cont.)
<div id="#myDiv">Farmers farm at Farmer's Market</div>
...(cont.) all I would need to do is use:
$("#myDiv").highlight("farm");
And then it would highlight the first four characters in "Farmers" and "Farmer's", as well as the entire word "farm" within the div#myDiv
No problem there, but I would like it to use this:
$("#myDiv").highlight("Farmers");
And have it highlight both "Farmers" AND "Farmer's". The problem is, of course, that I don't know the value of the search term (The term "Farmers" in this example) at runtime. So I would need to detect all possibilities of no more than one apostrophe at each index of the string. For instance, if I called $("#myDiv").highlight("Farmers"); like in my code example above, I would also need to highlight each instance of the original string, plus:
'Farmers
F'armers
Fa'rmers
Far'mers
Farm'ers
Farme'rs
Farmer's
Farmers'
Instances where two or more apostrophes are found sid-by-side, like "Fa''rmers" should, of course, not be highlighted.
I suppose it would be nice if I could include (to be highlighted) words like "Fa'rmer's", but I won't push my luck, and I would be doing well just to get matches like those found in my bulleted list above, where only one apostrophe appears in the string, at all.
I thought about regex, but I don't know the syntax that well, not to mention that I don't think I could do anything with a true/false return value.
Is there anyway to accomplish what I need here?
Things You May Want To Know:
The highlight plug-in takes care of all the case insensitive requirements I need, so no need to worry about that, at all.
Syntax provided in JavaScript, jQuery, or even C# is acceptable, considering the hidden input fields I use the values from, client-side, are populated, server-side, with my C# code.
The C# code that populates the hidden input fields uses Razor (i.e., I am in a C#.Net Web-Pages w/ WebMatrix environment. This code is very simple, however, and looks like this:
for (var n = 0; n < searchTermsArray.Length; n++)
{
<input class="highlightTerm" type="hidden" value="#searchTermsArray[n]" />
}
I'm copying this answer from your earlier question.
I think after reading the comments on the other answers, I've figured out what it is you're going for. You don't need a single regex that can do this for any possible input, you already have input, and you need to build a regex that matches it and its variations. What you need to do is this. To be clear, since you misinterpreted in your question, the following syntax is actually in JavaScript.
var re = new RegExp("'?" + "farmers".split("").join("'?") + "'?", "i")
What this does is take your input string, "farmers" and split it into a list of the individual characters.
"farmers".split("") == [ 'f', 'a', 'r', 'm', 'e', 'r', 's' ]
It then stitches the characters back together again with "'?" between them. In a regular expression, this means that the ' character will be optional. I add the same particle to the beginning and end of the expression to match at the beginning and end of the string as well.
This will create a regex that matches in the way you're describing, provided it's OK that it also matches the original string.
In this case, the above line builds this regex:
/'?f'?a'?r'?m'?e'?r'?s'?/
EDIT
After looking at this a bit, and the function you're using, I think your best bet will be to modify the highlight function to use a regex instead of a straight string replacement. I don't think it'll even be that hard to deal with. Here's a completely untested stab at it.
function innerHighlight(node, pat) {
var skip = 0;
if (node.nodeType == 3) {
var matchResult = pat.exec(node.data); // exec the regex instead of toUpperCase-ing the string
var pos = matchResult !== null ? matchResult.index : -1; // index is the location of where the matching text is found
if (pos >= 0) {
var spannode = document.createElement('span');
spannode.className = 'highlight';
var middlebit = node.splitText(pos);
var endbit = middlebit.splitText(matchResult[0].length); // matchResult[0] is the last matching characters.
var middleclone = middlebit.cloneNode(true);
spannode.appendChild(middleclone);
middlebit.parentNode.replaceChild(spannode, middlebit);
skip = 1;
}
}
else if (node.nodeType == 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) {
for (var i = 0; i < node.childNodes.length; ++i) {
i += innerHighlight(node.childNodes[i], pat);
}
}
return skip;
}
What I'm attempting to do here is keep the existing logic, but use the Regex that I built to do the finding and splitting of the string. Note that I'm not doing the toUpper call anymore, but that I've made the regex case insensitive instead. As noted, I didn't test this at all, but it seems like it should be pretty close to a working solution. Enough to get you started anyway.
Note that this won't get you your hidden fields. I'm not sure what you need those for, but this will (if it's right) take care of highlighting the string.
How to find whether a string array contains some part of string?
I have array like this
String[] stringArray = new [] { "abc#gmail.com", "cde#yahoo.com", "#gmail.com" };
string str = "coure06#gmail.com"
if (stringArray.Any(x => x.Contains(str)))
{
//this if condition is never true
}
i want to run this if block when str contains a string thats completely or part of any of array's Item.
Assuming you've got LINQ available:
bool partialMatch = stringArray.Any(x => str.Contains(x));
Even without LINQ it's easy:
bool partialMatch = Array.Exists(stringArray, x => str.Contains(x));
or using C# 2:
bool partialMatch = Array.Exists(stringArray,
delegate(string x) { return str.Contains(x)); });
If you're using C# 1 then you probably have to do it the hard way :)
If you're looking for if a particular string in your array contains just "#gmail.com" instead of "abc#gmail.com" you have a couple of options.
On the input side, there are a variety of questions here on SO which will point you in the direction you need to go to validate that your input is a valid email address.
If you can only check on the back end, I'd do something like:
emailStr = "#gmail.com";
if(str.Contains(emailStr) && str.length == emailStr.length)
{
//your processing here
}
You can also use Regex matching, but I'm not nearly familiar enough with that to tell you what pattern you'd need.
If you're looking for just anything containing "#gmail.com", Jon's answer is your best bets.
In my attempt at dissecting a bit of C# I am afraid I do not understand either the goal or the logic of this bit of code:
if (!string.IsNullOrEmpty(str2) && (Strings.UCase(Strings.Left(str2, 1)) != Strings.Left(str2, 1)))
{
return false;
}
I understand the first part is checking if str2 is "not null", however the second part is coming off a bit flaky. So we UCase the first character of str2, and if it does not equal the first character of str2 (which is NOT "UCase"d), then return "false"?
Maybe I am not missing anything and what I described above is in fact what the code is doing. If this is the case, can we reform this into something else that offers the same result,say for example, check if str2 is uppercase or not? I feel like this is the end goal.
You thoughts?
Yes, you understood the code right.
It looks like something translated from VB using a translation tool, as it's using functions from the VisualBasic namespace. I would rather write it with String methods:
if (!String.IsNullOrEmpty(str2) && str2.Substring(0,1).ToUpper() != str2.SubString(0,1)) {
return false;
}
Or simply getting the first character as a character instead of as a string, and use the IsLower method of the Char class:
if (!string.IsNullOrEmpty(str2) && Char.IsLower(str2[0])) {
return false;
}
My bet is that they are really just testing whether the first character is uppercase. The initial "IsNullOrEmpty" test is just there to make sure that the real test doesn't throw an exception.
The big question: if there is no string value (null or empty) this will not return false. Is that the expected outcome?
Code Objective in English :)
If the non-empty string begins with a lower case character then return false
This is the same, but refactored:
if (!string.IsNullOrEmpty(str2)) {
string s = Strings.Left(str2, 1);
if (Strings.UCase(s) != s) {
return false;
}
}
It is clear that this code tests that the first letter of str2 is or isn't in uppercase when it has any character.
I share the perceptions you have when you say : "I do not understand either the goal or the logic of this bit of code" :) A test that returns only 'false is "fishy" : presumably "something" is waiting for a boolean to be returned, and nothing is returned if the result of this evaluates to 'true.
But if I had to write such a function I'd use the alternative OR logic :
return (! (String.IsNullOrEmpty(testString) || testString.ToUpper()[0] == testString[0]));
I'm trying to maniplulate a string without making a big issue out of it and spreading it out onto multiple lines, so I'm using some chaining to achieve this. The question I have is, how do I use string.Substring() to drop the last character off my string in this context?
In PHP I can pass a negative number as an argument (i.e. substr(-1)) to achieve this, but obviously this isn't how C# works.
mystring = mystring.Replace('_', ' ').Substring(???);
Also, what is the actual name for the technique used above? I always referred to it as a callback chain, but a callback chain I now think is something completely different.
Please note I want to avoid:
mystring = mystring.Replace('_', ' ');
mystring = mystring.Substring(0, mystring.Length - 1);
Thanks in advance for your time and kind consideration.
Iain
Thanks for your answers guys. It's funny that people can have such strong opinions about string manipulation and other "competing" languages :)
You could write an Extension method RightStrip(). You can't overload SubString for negative start positions.
static string RightStrip(this string s, int n)
{
return s.Substring(0, s.Length - n);
}
string s = "Hello World!";
s = s.Replace('e', 'a').RightStrip(1);
Create an extension class like this:
public static class MyStringExtensions
{
public static string RemoveCharactersFromEnd(this string s, int n)
{
string result = string.Empty;
if (string.IsNullOrEmpty(s) == false && n > 0)
{
result = s.Remove(s.Length - n, n);
}
return result;
}
}
Call it:
Console.WriteLine("test!!".RemoveCharactersFromEnd(2));
In your sample, you are chaining to a method that doesn't change the length of the original string. Hence answers suggesting using SubString with (originalLength-1), which of course doesn't work in the general case.
The answer as you seem to have realized is - you can't do it in the general case, where previous methods in the chain have modified the length.
But you can write your own extension method in 3.5 to do what you want. Something like the following or a variant thereof:
public static string PhpSubstring(this string value, int length)
{
if (length < 0) length = value.Length - length;
return String.Substring(value, length);
}
Besides everyone else mentioning the term method chaining, or what some call a fluent interface, I had a note or two I wanted to add.
What I wanted to suggest is that the cool thing about extension methods is that you can easily define your own type of transformation functions that feel the same as this, including system methods such as Replace and ToLower, etc.... something that takes some input and returns some kind of transformed string.
The particular transformation you are asking for (cut off the right-most char) might seem clunky if you have to use Substring directly, but you can hide this away neatly in something like:
public string CutOff(this string s, int c)
{
return s.Substring(0, s.Length - c);
}
...
return myVal.CutOff(1);
(or at least, i think this should work!)
Best of luck!
Method chaining is the term you're looking for. It's true that you cannot pass a negative character like that, but you can still chain the methods:
mystring = mystring.Replace('_', ' ').Substring(0, mystring.Length - 1);
since the string replace in this case, does not affect the length of the string
mystring = mystring.Replace('_', ' ').Remove(mystring.length -1)
However I would consider this a bad idea since the assignment of mystring doesn't happen until after all the manipulation and change in the length of the string in previous calls will result in unexpected behavior.
To further Konamiman's comment:
Just because PHP allows bizarre (and frankly dirty and dangerous) overloads and parameters such as negative starts and counts in SubString, it doesn't mean it's the right, correct or proper way of doing it.
Substring(0, mystring.Length - 1) is the de facto way of trimming off the last character of a string in a wide variety of languages.
You could always use regex:
mystring = new Regex("^(.*).$").Match(mystring.Replace('_', ' ')).Groups[1].Value;
Also, since you're just going to remove that last character, it does not matter if it was a '_' that got replaced by a ' '. This would work just fine:
mystring = mystring.Substring(0, mystring.Length - 1).Replace('_', ' ');