Compare string with character in C# - c#

suppose there is a string like this
string temp2 = "hello";
char[] m = { 'u','i','o' };
Boolean B = temp2.Compare(m);
I want to check if the string contains my array of character or not?
I am trying but it is not taking.On compiling the message
temp2.Compare(m) should be String type
is coming.
Means it follows string.compare(string);
I hope it is not the way there should be some way to do that.
edit//
I have Corrected the line String.Compare return the Boolean Value

If what you want to determine is whether the string contains any of the characters in your array, you can use the string.IndexOfAny function.
bool containsAny = temp2.IndexOfAny(m) >= 0;

Related

How to get the char from a string that contains unicode escape sequence which starts with "\u"

I did quite a lot of researches but still could not figure it out. Here is an example, I got a string contains "\uf022" (a character from another language), how can I change the whole string into the char '\uf022'?
Update:
the string "\uf022" is retrieved during runtime (read from other sources) instead of directly putting a static character into the string.
For example:
string url = "https://somesite/files/abc\uf022def.pdf";
int i = url.IndexOf("\\");
string specialChar = url.substring(i, 6);
How do I get the char saved in the string specialChar?
I would like to use this char to do UTF-8 encoding and generate the accessible URL "https://somesite/files/abc%EF%80%A2def.pdf".
Thank you!
how can I change the whole string into the char '\uf022'?
Strictly speaking, you can't change the characters of the string you have (because strings are immutable), but you can make a new one that meets your demands..
var s = new string('\uf022', oldstring.Length);
Your title of your question reads slightly differently.. it sounds like you want a string that is only the F022 chars, i.e. if your string has 10 chars and only 3 of them are F022, you want just the 3.. which could be done by changing oldstring.Length above, into oldstring.Count(c => c == '\uf022')
..and if you mean your string is like "hello\uf022world" and you want it to be like "hello🍄world" then do
var s = oldstring.Replace("\\uf022", "\uf022");
If you have the \uf022 in a string (6 chars) and you want to replace it with its actual character, you can parse it to int and convert to char when you replace..
var oldstring = "hello\uf022world";
var given = "\uf022";
var givenParsed = ((char)Convert.ToInt32(given.Substring(2), 16)).ToString();
var s = oldstring.Replace(given, givenParsed);

Extract string parts that are separated with commas

I need to extract a string into 3 different variables.
The input from the user will be in this format 13,G,true.
I want to store the number in an integer, the "G" in a character and "true" into a string.
But I don't know how to specify the comma location so the characters before or after the comma can be stored in another variable.
I'm not allowed to use the LastIndexOf method.
string msg = "13,G,true";
var myArray = msg.Split(",");
// parse the elements
int number;
if (!Int32.TryParse(myArray[0], out number) throw new ArgumentException("Whrong input format for number");
string letter = myArray[1];
string b = myArry[2];
// or also with a boolean instead
bool b;
if (!Int32.TryParse(myArray[2], out b) throw new ArgumentException("Whrong input format for boolean");
use String.Split
string str='13,G,true';
string[] strArr=str.Split(',');
int32 n=0,intres=0;
char[] charres = new char[1];
string strres="";
if(!Int32.TryParse(strArr[0], out n))
{
intres=n;
}
if(strArr[0].length>0)
{
charres[0]=(strArr[1].toString())[0];
}
strres=strArr[2];
//you'll get 13 in strArr[0]
//you'll get Gin strArr[1]
//you'll get true in strArr[2]
var tokens = str.Split(","); //Splits to string[] by comma
var first = int32.Parse(tokens[0]); //Converts first string to int
var second = tokens[1][0]; //Gets first char of the second string
var third = tokens[2];
But be aware, that you also need to validate the input
You are going to need method String.Split('char'). This method splits string using specified char.
string str = "13,G,true";
var arrayOfStrings=str.Split(',');
int number = int.Parse(arrayOfStrings[0]);
// original input
string line = "13,G,true";
// splitting the string based on a character. this gives us
// ["13", "G", "true"]
string[] split = line.Split(',');
// now we parse them based on their type
int a = int.Parse(split[0]);
char b = split[1][0];
string c = split[2];
If what you are parsing is CSV data, I would check out CSV parsing libraries related to your language. For C#, Nuget.org has a few good ones.

Get a part of string

I have a string as
"cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc_197"
I want to fetch the last digits(i.e. 197)
For obtaining same i have implemented below code
int lastUnderscore = addUcoid.LastIndexOf('_');
string getucoid = addUcoid.Substring(lastUnderscore).TrimStart('_');
The getucoid string gets the digit part properly.The problem now is that I have to also check if the digits occur in string,i.e. string can be like
"cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc"
How to perform the check on such string, whether that part(197) exists at the end in the string or not.
Here 197 is just an example.It could be any numeric data,for example 196,145,etc
string.Contains won't help: we know it is there at least once already. I would use:
int otherLocation = addUcoid.IndexOf(getucoid);
and compare this to lastUnderscore. If otherLocation is non-negative and less than lastUnderscore, then it is there in an earlier position too. You could also use:
int otherLocation = addUcoid.IndexOf(getucoid, 0, lastUnderscore);
and compare to -1; this second approach stops at the underscore, so won't find the instance from the end.
I think Regex is the easiest way. If match.Success is true the digits have been found.
Match match = System.Text.RegularExpressions.Regex.Match(addUcoid, #"(?<=_)\d+$");
if(match.Success)
{
int i = int.Parse(match.Value);
}
I suspect you just want to know if this last part is a numeric or not:
bool isNumeric = Regex.IsMatch(getucoid, #"^\d+$");
Use String.EndsWith method to findout.
http://msdn.microsoft.com/en-us/library/2333wewz%28v=vs.110%29.aspx
string s="cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc";
bool isends=s.EndsWith("197");//returns false;
s="cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc_197";
isends=s.EndsWith("197");//returns true;
The presence of a substring can be checked with String.Contains(): http://msdn.microsoft.com/en-us/library/dy85x1sa%28v=vs.110%29.aspx
Assuming you have removed the final "_197" after checking that it exists, calling Contains("197") on your string will return true if "197" is a substring, or false if it isn't.
You can use LINQ (also to check if the last char is a digit):
string str = "cmp197_10_27_147ee7b825-2a3b-4520-b36c-bba08f8b0d87_TempDoc_197";
if (Char.IsDigit(str.Last()))
{
string digits = new string(str.Reverse().TakeWhile(c => Char.IsDigit(c)).Reverse().ToArray());
}
When you say exists at the "end in the string", do you mean if it exists anywhere in the string? You can do a .Contains() to get it.
bool inTheString = addUcoid.Contains(getucoid);
Also:
FYI, your code:
int lastUnderscore = addUcoid.LastIndexOf('_');
string getucoid = addUcoid.Substring(lastUnderscore).TrimStart('_');
can be simplified shortened into:
string getucoid = addUcoid.Split('_').Last();
EDIT:
Ehm, Marc Gravell rightly points out that the string is there anyway. If you want to find out if another instance of the string is there (aside from getucoid):
int lastUnderscore = addUcoid.LastIndexOf('_');
string getucoid = addUcoid.Split('_').Last();
bool inTheString = addUcoid.Substring(0,lastUnderscore).Contains(getucoid);

How do I check the number of occurences of a certain string in another string?

string containsCharacter = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(containsCharacter).Length - 1;
I originally pulled this code off another person's question's answer but it doesn't seem to work with text boxes.
Errors I'm getting:
The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Argument 1: cannot convert from 'string' to 'char[]'
I prefer to fix this code rather than use other things like LINQ but I would accept it if there isn't a way to fix this code.
You could iterate through the characters
string value = "BANANA";
int x = 0;
foreach (char c in value)
{
if (c == 'A')
x++;
}
string containsCharacter = "t";
string testString = "test string contains certain characters";
int count = testString.Count(x => x.ToString() == containsCharacter);
This example will return 6.
The Split version you are using expects a character as input. This is the version for strings:
string containsText = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(new string[]{containsText}, StringSplitOptions.None).Length - 1;
With this code, count will be: 1 if textBox1.Text includes "test", 6 if it contains "t", etc. That is, it can deal with any string (whose length might be one, as a single character, or as big as required).
You can call ToCharArray on the string to make it a char[], like this:
int count = testString.Split(containsCharacter.ToCharArray()).Length - 1;
Since Split takes characters as a param, you could rewrite this by listing the characters being counted directly, as follows:
int count = testString.Split(',', ';', '-').Length - 1;
"this string. contains. 3. dots".Split(new[] {"."}, StringSplitOptions.None).Count() - 1
Edit:
Upon Reading your code more carefully I suggest you do this, you should rephrase your question to
"Check the number of occurences of a certain string in Another string":
string containsString = "this";
string test = "thisisateststringthisisateststring";
var matches = Regex.Matches(test,containsString).Count;
matches is 2!
My initial post answers your actual question "occurrences of a certain character in a string":
string test = "thisisateststring";
int count = test.Count(w => w == 'i');
Count is 3!

Convert alphabetic string into Integer in C#

Is it possible to convert alphabetical string into int in C#? For example
string str = "xyz";
int i = Convert.ToInt32(str);
I know it throws an error on the second line, but this is what I want to do.
So how can I convert an alphabetical string to integer?
Thanks in advance
System.Text.Encoding ascii = System.Text.Encoding.ASCII;
string str = "xyz";
Byte[] encodedBytes = ascii.GetBytes(str);
foreach (Byte b in encodedBytes)
{
return b;
}
this will return each characters ascii value... its up to you what you want to do with them
To answer the literal questions that you have asked
Is it possible to convert alphabetical string into int in C#?
Simply put... no
So how can I convert an alphabetical string to integer?
You cannot. You can simply TryParse to see if it will parse, but unless you calculate as ASCII value from the characters, there is no built in method in c# (or .NET for that matter) that will do this.
You can check whether a string contains a valid number using Int32.TryParse (if your questions is about avoiding an exception to be thrown):
int parsed;
if (!Int32.TryParse(str, out parsed))
//Do Something

Categories

Resources