I need to count the number of points at the END of string.
The number of points in the middle of the string are not relevant and should not be countet.
How can this be done?
string sample = "This.is.a.sample.string.....";
for the example above the correct answer would be 5 because there are 5 points at the end of the string.
because of performace reasons I would prefer a fast solution. Don't know if Regular Expressions
\.*$
should be used in such a case.
Start from the end of the string and go back char by char until its not a dot:
string sample = "This.is.a.sample.string....."
int count = 0;
for (int i = sample.Length - 1; i >= 0; i--)
{
if (sample[i] != '.') break;
count++;
}
Using Linq:
var test = "this.is.a.test........";
var count = test.ToCharArray().Reverse().TakeWhile(q => q == '.').Count();
Convert string to array, reverse, then take while character = '.'. Count result.
A simple solution using an extension method.
var test = "this.is.a.test........";
Console.WriteLine(test.CountTrailingDots());
public static int CountTrailingDots(this string value)
{
return value.Length - value.TrimEnd('.').Length;
}
Using Regex:
int points = Regex.Match("This.is.a.sample.string....", #"^[\w\W]*?([.]*+)$").Groups[1].Value.Length;
Description:
*+ = Matches as many characters as possible
*? = Matches as few characters as possible.
It can be something like..
string sample = "This.is.a.sample.string.....";
int count = 0;
if(sample.EndsWith("."))
count = sample.Substring(sample.TrimEnd('.').Length).Length;
Related
I've got various string in a list:
Ord.cl. N. 2724 del 08/11/2019
and it can be also
Ord.cl. N. 2725/web del 08/11/2019
I have to take all the content that comes after 'N.' and before 'del'. As result I want
2724
2725/web
Can someone do code for that in C#? I know there is substring, but maybe there are better ways?
you can build some extention method like this
public string SubstringFromTo(this string input, int from, int to)
{
return input.Substring(from, (to - from));
}
public string SubstringFromTo(this string input, string from, string to)
{
var index1 = input.IndexOf(from) != -1 ? input.IndexOf(from) : 0;
var index2 = input.IndexOf(to) != -1 ? input.IndexOf(to) : (input.Length - 1);
return input.SubstringFromTo(index1, index2);
}
var asd = " ciao ** come stai ? asdasd".SubstringFromTo("**","?");
result = "come stai"
//.Trim() if you want
Using regular expressions, you might do:
var m = Regex.Match("Ord.cl. N. 2724 del 08/11/2019", #"(?<=N\.).*?(?=del)");
if (m.Success)
{
var result = m.Value;
}
Explanation of the regular expression:
(?<=N\.) looks for a preceding "N.".
.*? matches any sequence of characters, but as few as possible
(?=del) lools for a trailng "del".
If it's always that predictable (space before and after N. and space before and after del), then it's fairly simple. Use Substring and use IndexOf to find the occurrences of N. and del:
var theString = "Ord.cl. N. 2725/web del 08/11/2019";
var start = theString.IndexOf("N. ") + 3;
var length = theString.IndexOf(" del", start) - start;
var partIWant = theString.Substring(start, length).Trim();
Console.WriteLine(partIWant);
That also assumes that there will only ever be one occurrence of N. and del in your string.
for (int i = 0; i< list.Count-1; i++)
{
NDocList.Add(list[i].DocumentiOrigine.Split(new string[] { " N. " }, StringSplitOptions.None)[1]
.Split()[0]
.Trim());
}
solved with this somehow.
I need to capitalize everything before the second - from the beginning of the string in .NET. What is the best way to do this? The string before the second dash can be anything. I need a new single string once this is complete.
Before
Tt-Fga - Louisville - Kentucky
After
TT-FGA - Louisville - Kentucky
This should get the job done for your specific case:
public static string ToUpperUntilSecondHyphen(string text)
{
int index = text.IndexOf('-', text.IndexOf('-') + 1);
return text.Substring(0, index).ToUpper() + text.Substring(index);
}
A more generalized method could look something like this:
public static string ToUpperUntilNthOccurrenceOfChar(string text, char c, int occurrences)
{
if (occurrences > text.Count(x => x == c))
{
return text.ToUpper();
}
int index = 0;
for (int i = 0; i < occurrences; i++, index++)
{
index = text.IndexOf(c, index);
}
return text.Substring(0, index).ToUpper() + text.Substring(index);
}
Identify the location of the hyphen with IndexOf. You'll have to use this function twice so that you can find the first hyphen, and then the second one.
Construct the substring that only contains the characters up to that with Substring. Construct the substring that contains all the remaining characters as well.
Upper case the first string with ToUpper.
Concatenate with the + operator.
(.*?-.*)(?=-)
You can use replace here.Replace with $1.upper() or something which is available in c#.
See
http://regex101.com/r/yR3mM3/50
I went ahead and did this. If there is a better answer let me know.
var parts = #event.EventParent.Name.Split(new[] {'-'}, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
if (i >= 2)
break;
parts[i] = parts[i].ToUpper();
}
#event.EventParent.Name = string.Join("-", parts);
I want to find the index of first capital letter occurrence in a string.
E.g. -
String x = "soHaM";
Index should return 2 for this string. The regex should ignore all other capital letters after the first one is found. If there are no capital letters found then it should return 0. Please help.
I'm pretty sure all you need is the regex A-Z \p{Lu}:
public static class Find
{
// Apparently the regex below works for non-ASCII uppercase
// characters (so, better than A-Z).
static readonly Regex CapitalLetter = new Regex(#"\p{Lu}");
public static int FirstCapitalLetter(string input)
{
Match match = CapitalLetter.Match(input);
// I would go with -1 here, personally.
return match.Success ? match.Index : 0;
}
}
Did you try this?
Just for fun, a LINQ solution:
string x = "soHaM";
var index = from ch in x.ToArray()
where Char.IsUpper(ch)
select x.IndexOf(ch);
This returns IEnumerable<Int32>. If you want the index of the first upper case character, simply call index.First() or retrieve only the first instance in the LINQ:
string x = "soHaM";
var index = (from ch in x.ToArray()
where Char.IsUpper(ch)
select x.IndexOf(ch)).First();
EDIT
As suggested in the comments, here is another LINQ method (possibly more performant than my initial suggestion):
string x = "soHaM";
x.Select((c, index) => new { Char = c, Index = index }).First(c => Char.IsUpper(c.Char)).Index;
No need for Regex:
int firstUpper = -1;
for(int i = 0; i < x.Length; i++)
{
if(Char.IsUpper(x[i]))
{
firstUpper = i;
break;
}
}
http://msdn.microsoft.com/en-us/library/system.char.isupper.aspx
For the sake of completeness, here's my LINQ approach(although it's not the right tool here even if OP could use it):
int firstUpperCharIndex = -1;
var upperChars = x.Select((c, index) => new { Char = c, Index = index })
.Where(c => Char.IsUpper(c.Char));
if(upperChars.Any())
firstUpperCharIndex = upperChars.First().Index;
First your logic fails, if the method returns 0 in your case it would mean the first char in that list was in upperCase, so I would recomend that -1 meens not found, or throw a exception.
Anyway just use regular expressions becasue you can is not always the best choise, plus they are pretty slow and hard to read in general, making yoru code much harder to work with.
Anyway here is my contribution
public static int FindFirstUpper(string text)
{
for (int i = 0; i < text.Length; i++)
if (Char.IsUpper(text[i]))
return i;
return -1;
}
Using Linq:
using System.Linq;
string word = "soHaMH";
var capChars = word.Where(c => char.IsUpper(c)).Select(c => c);
char capChar = capChars.FirstOrDefault();
int index = word.IndexOf(capChar);
Using C#:
using System.Text.RegularExpressions;
string word = "soHaMH";
Match match= Regex.Match(word, "[A-Z]");
index = word.IndexOf(match.ToString());
Using loop
int i = 0;
for(i = 0; i < mystring.Length; i++)
{
if(Char.IsUpper(mystring, i))
break;
}
i is the value u should be looking at;
I would like to find the count of Exact match of string
Let suppose string is 'My Computer'. I want to find it,s occurrence in string
This is My computer,this is a good Computer,this is my Computer,this is my Computers
So at end I shall get Count 2 ,
I have tried the following formula with 'mykeyWord' as string to be found.
int strength = (innerDocument.DocumentNode.InnerText.Length - innerDocument.DocumentNode.InnerText.ToLower().Replace(mykeyWord.ToLower(), "").Length) / mykeyWord.Length;
But it will also count strings like 'my Computers' that is wrong.
This is a perfect place to use regular expressions, just as you tagged your post:
Regex re = new Regex("\\b" + Regex.Escape(mykeyWord) + "\\b", RegexOptions.IgnoreCase);
int count = re.Matches(innerDocument.DocumentNode.InnerText).Count;
You could use the regular expression [^A-z](my computer)[^A-z] This matches 'my computer' but not if it's before or after 'A to Z'. To make the regex search case insensitive use RegexOptions.IgnoreCase.
Edit
minitech's answer using word boundaries is better.
int FindCount(string keyword, string input)
{
if (input.Contains(keyword))
{
int count = 0;
int i = 0;
foreach (var c in input)
{
if (c == keyword[i])
i++;
else
i = 0;
if (i == keyword.Length)
{
i = 0;
count++;
}
}
return count;
}
return 0;
}
i have a string like this:
some_string = "A simple demo of SMS text messaging.\r\n+CMGW: 3216\r\n\r\nOK\r\n\"
im coming from vb.net and i need to know in c#, if i know the position of CMGW, how do i get "3216" out of there?
i know that my start should be the position of CMGW + 6, but how do i make it stop as soon as it finds "\r" ??
again, my end result should be 3216
thank you!
Find the index of \r from the start of where you're interested in, and use the Substring overload which takes a length:
// Production code: add validation here.
// (Check for each index being -1, meaning "not found")
int cmgwIndex = text.IndexOf("CMGW: ");
// Just a helper variable; makes the code below slightly prettier
int startIndex = cmgwIndex + 6;
int crIndex = text.IndexOf("\r", startIndex);
string middlePart = text.Substring(startIndex, crIndex - startIndex);
If you know the position of 3216 then you can just do the following
string inner = some_string.SubString(positionOfCmgw+6,4);
This code will take the substring of some_string starting at the given position and only taking 4 characters.
If you want to be more general you could do the following
int start = positionOfCmgw+6;
int endIndex = some_string.IndexOf('\r', start);
int length = endIndex - start;
string inner = some_string.SubString(start, length);
One option would be to start from your known index and read characters until you hit a non-numeric value. Not the most robust solution, but it will work if you know your input's always going to look like this (i.e., no decimal points or other non-numeric characters within the numeric part of the string).
Something like this:
public static int GetNumberAtIndex(this string text, int index)
{
if (index < 0 || index >= text.Length)
throw new ArgumentOutOfRangeException("index");
var sb = new StringBuilder();
for (int i = index; i < text.Length; ++i)
{
char c = text[i];
if (!char.IsDigit(c))
break;
sb.Append(c);
}
if (sb.Length > 0)
return int.Parse(sb.ToString());
else
throw new ArgumentException("Unable to read number at the specified index.");
}
Usage in your case would look like:
string some_string = #"A simple demo of SMS text messaging.\r\n+CMGW: 3216\r\n...";
int index = some_string.IndexOf("CMGW") + 6;
int value = some_string.GetNumberAtIndex(index);
Console.WriteLine(value);
Output:
3216
If you're looking to extract the number portion of 'CMGW: 3216' then a more reliable method would be to use regular expressions. That way you can look for the entire pattern, and not just the header.
var some_string = "A simple demo of SMS text messaging.\r\n+CMGW: 3216\r\n\r\nOK\r\n";
var match = Regex.Match(some_string, #"CMGW\: (?<number>[0-9]+)", RegexOptions.Multiline);
var number = match.Groups["number"].Value;
More general, if you don't know the start position of CMGW but the structure remains as before.
String s;
char[] separators = {'\r'};
var parts = s.Split(separators);
parts.Where(part => part.Contains("CMGW")).Single().Reverse().TakeWhile(c => c != ' ').Reverse();