Count numbers of \r\r in a string [duplicate] - c#

This question already has answers here:
How to count of sub-string occurrences? [duplicate]
(8 answers)
Closed 8 years ago.
I want to count, how often I have \r\r in a string variable.
For example:
string sampleString = "9zogl22n\r\r\nv4bv79gy\r\r\nkaz73ji8\r\r\nxw0w91qq\r\r\ns05jxqxx\r\r\nw08qsxh0\r\r\nuyggbaec\r\r\nu2izr6y6\r\r\n106iha5t\r";
The result would be in this example 8.

You can use a regular expression:
var res = Regex.Matches(s, "\r\r").Count;
Or a loop over the string:
var res = 0;
for (int i = 0; i < str.Length - 1; i++)
if(s[i] == '\r' && s[i + 1] == '\r')
res++;

Try this method:
public static int CountStringOccurrences(this string text, string pattern)
{
int count = 0;
int i = 0;
while ((i = text.IndexOf(pattern, i)) != -1)
{
i += pattern.Length;
count++;
}
return count;
}
Usage:
int doubleLinefeedCount = sampleString.CountStringOccurrences("\r\r");

You can use LINQ to select all positions where \r\r start and count them:
Enumerable.Range(0, s.Length).Where(idx => s.IndexOf(#"\r\r", idx)==idx).Count();
Note that "\r\r\r" will return 2 in above code...

You can use the trick of splitting the string with your lookup charachter \r\r:
(this is not really efficient _ we need to allocate 2 string arrays _ but I post it as a possible solution, particularly if the separated tokens are of any interest to you)
"9zogl22n\r\r\nv4bv79gy\r\r\nkaz73ji8\r\r\nxw0w91qq\r\r\ns05jxqxx\r\r\nw08qsxh0\r\r\nuyggbaec\r\r\nu2izr6y6\r\r\n106iha5t\r".Split(new string[] {"\r\r"}, StringSplitOptions.None).Length - 1)

You can write a simple extension method for that:
public static int LineFeedCount(this string source)
{
var chars = source.ToCharArray();
bool found = false;
int counter = 0;
int count = 0;
foreach(var ch in chars)
{
if (ch == '\r') found = true;
else found = false;
if (found) counter++;
else counter = 0;
if(counter != 0 && counter%2 == 0) count++;
}
return count;
}
Then use it:
int count = inputString.LineFeedCount();

Related

How to find biggest substring from string1 into string2

Lets suppose i have two strings string1 and string2.
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from, with no signup needed";
I need to find biggest substring of string1 which matches in string2.
here biggest substring will be "canadian geese" which is matching in string2.
How can I find it? I tried breaking string1 into char[] and find words then merged matched words but that failed my objective.
classy loop approach - the result includes te space after geese "canadian geese "
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from, with no signup needed";
string result = "";
for (int i = 0; i < string1.Length; i++)
{
for (int j = 0; j < string1.Length - i; j++)
{
//add .Trim() here if you want to ignore space characters
string searchpattern = string1.Substring(i, j);
if (string2.IndexOf(searchpattern, StringComparison.OrdinalIgnoreCase) > -1 && searchpattern.Length > result.Length)
{
result = searchpattern;
}
}
}
https://dotnetfiddle.net/q3rHjI
Side note:
canadian and Canadian are not equal so you have to use StringComparison.OrdinalIgnoreCase if you want to search case insensitive
Have a look at the following code https://dotnetfiddle.net/aPyw3o
public class Program {
static IEnumerable<string> substrings(string s, int length) {
for (int i = 0 ; i + length <= s.Length; i++) {
var ss = s.Substring(i, length);
if (!(ss.StartsWith(" ") || ss.EndsWith(" ")))
yield return ss;
}
}
public static void Main()
{
int count = 0;
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from, with no signup needed";
string result = null;
for (int i = string1.Length; i>0 && string.IsNullOrEmpty(result); i--) {
foreach (string s in substrings(string1, i)) {
count++;
if (string2.IndexOf(s, StringComparison.CurrentCultureIgnoreCase) >= 0) {
result = s;
break;
}
}
}
if (string.IsNullOrEmpty(result))
Console.WriteLine("no common substrings found");
else
Console.WriteLine("'" + result + "'");
Console.WriteLine(count);
}
}
The substrings method returns all substrings of the string s with the length of length (for the yield have a look at the documentation https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield) We skip substrings that start or end with a space, as we don't want whitespaces to make a substring longer than it really is)
The outer loop iterates through all the possible length values for the substrings, from the longest (ie string1.Length) to the shortest (ie 1). Then for each of the found substrings of length i is checked, if it's also a substring of string2. If that's the case, we can stop, as there cannot be any longer common substring, because we checked all longer substrings in previous iterations. But of course there may be other common substrings with length i
I'm going to add one more, using span/readonlymemory so you can avoid allocating all the strings that the current answers create. Note I didn't do any check for starting space or ending space as that does not seem to be a requirement for the question. This does do a case insensitive search, if you don't want that you can make it more efficient by using the built in indexof and dropping the case insensitive compares.
static void Main(string[] _)
{
var string1 = "images of canadian geese goslings";
var string2 = "Canadian geese with goslings pictures to choose from, with no signup needed";
var longest = FindLongestMatchingSubstring(string1, string2);
Console.WriteLine(longest);
}
static string FindLongestMatchingSubstring(string lhs, string rhs)
{
var left = lhs.AsMemory();
var right = rhs.AsMemory();
ReadOnlyMemory<char> longest = ReadOnlyMemory<char>.Empty;
for (int i = 0; i < left.Length; ++i)
{
foreach (var block in FindMatchingSubSpans(left, i, right))
{
if (block.Length > longest.Length)
longest = block;
}
}
if (longest.IsEmpty)
return string.Empty;
return longest.ToString();
}
static IEnumerable<ReadOnlyMemory<char>> FindMatchingSubSpans(ReadOnlyMemory<char> source, int pos, ReadOnlyMemory<char> matchFrom)
{
int lastMatch = 0;
for (int i = pos; i < source.Length; ++i)
{
var ch = source.Span[i];
int match = IndexOfChar(matchFrom, lastMatch, ch);
if (-1 != match)
{
lastMatch = match + 1;
int end = i;
while (++end < source.Length && ++match < matchFrom.Length)
{
char lhs = source.Span[end];
char rhs = matchFrom.Span[match];
if (lhs != rhs && lhs != (char.IsUpper(rhs) ? char.ToLower(rhs) : char.ToUpper(rhs)))
{
break;
}
}
yield return source.Slice(i, end - i);
}
}
}
static int IndexOfChar(ReadOnlyMemory<char> source, int pos, char ch)
{
char alt = char.IsUpper(ch) ? char.ToLower(ch) : char.ToUpper(ch);
for (int i = pos; i < source.Length; ++i)
{
char m = source.Span[i];
if (m == ch || m == alt)
return i;
}
return -1;
}

how to ignore characters when copying from one string to another - c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
How can I ignore characters between /* */ in string when copying to another string?
string str1 = "/*TODO:if*/";
How to ignore the caracters between /**/ so the new string will look like this:
string str2 = "/**/";
I am not allowed to use any library functions!
string str2 = Regex.Replace(str1, #"/\*.*\*/", "/**/");
Using a regular expression, you can capture all instances of /*[anything]*/ and replace it with just the text you want: /**/. However, this will be very greedy. If you have the string /*foo*/bar/*baz*/, this will eat all of it.
string str2 = Regex.Replace(str1, #"/\*.+?\*/", "/**/");
By changing it to be a lazy regex, the string /**/bar/**/ will be returned.
Given the edit above, this could also be done without Regex by doing a simple index search - though it is a greedy replacement.
string str2 = str1.Substring(0, str1.IndexOf("/*")) + "/*" + str1.Substring(str1.LastIndexOf("*/"));
This just takes everything before the first /* and then everything after the last */.
Try this code (it does not use any library function):
static string FormatString(string str) =>
RemoveAfter(str, "/*") + SubstringFrom(str, "*/");
static int IndexOf(string str, string value)
{
for (int i = 0; i < str.Length - value.Length; i++)
{
bool found = true;
for (int j = 0; j < value.Length; j++)
{
if (str[i + j] != value[j])
{
found = false;
break;
}
}
if (found)
{
return i;
}
}
return -1;
}
static int LastIndexOf(string str, string value)
{
for (int i = str.Length - value.Length; i >= 0; i--)
{
bool found = true;
for (int j = 0; j < value.Length; j++)
{
if (str[i + j] != value[j])
{
found = false;
break;
}
}
if (found)
{
return i;
}
}
return -1;
}
static string SubstringFrom(string str, string value)
{
int startIndex = LastIndexOf(str, value);
int length = str.Length - startIndex;
char[] result = new char[length];
for (int i = 0; i < length; i++)
{
result[i] = str[startIndex + i];
}
return new string(result);
}
static string RemoveAfter(string str, string value)
{
int length = IndexOf(str, value) + value.Length;
char[] result = new char[length];
for (int i = 0; i < length; i++)
{
result[i] = str[i];
}
return new string(result);
}
I'm not sure it makes sense that you can't use library functions, considering all functions are essentially library functions. I think the limitation here is that you can't bring in a library that doesn't already come imported in a new project. That's OK, we can do this hobbled like that. The Type string has a Split function, and failing that we can play it dirty and use indeces like it's 1995. I didn't get to test these but you should be well on your way with them. It was a fun little exercise, honestly.
Given : string str1 = "Stufftokeep/*TODO:if*/StufftokeepAgain";
string[] crazyHomework = str1.Split('/');
string result = string.Empty;
foreach(string s in crazyHomework)
{
if(s.IndexOf('*') == -1)
result += s + " "; //added a space to keep them separate
}
That gets you there using only System functions. Failing that, you can mutate the string into a lovely array of type char (which is all a string is anyway).
string result = string.Empty;
bool copy = true;
char[] array = str1.ToCharArray()
foreach(char a in array)
{
int i = array.IndexOf[a];
if(a == "/" && array.IndexOf(a) != array.Length - 1
&&
(array[a + 1] == '*' || array[a -1] == '*'))
{
copy = !copy;
}
if(copy)
result += a.ToString();
}
You'll have some space issues on that one if there isn't whitespace in the string, though.
Quick and dirty
string temp = null;
string str1 = "this shoudl remain/*TODO:if*/*/*testing again */-and so should this";
int x, y;
while ((x = str1.IndexOf("/*")) != -1)
{
if ((y = str1.IndexOf("*/")) > x)
{
temp += str1.Substring(0, x + 2) + str1.Substring(y, 2);
str1 = str1.Substring(y + 2);
continue;
}
temp += str1.Substring(y, x);
str1 = str1.Substring(x)
}
temp += str1;

Splitting text into lines with maximum length

I have a long string and I want to fit that in a small field. To achieve that, I break the string into lines on whitespace. The algorithm goes like this:
public static string BreakLine(string text, int maxCharsInLine)
{
int charsInLine = 0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
builder.Append(c);
charsInLine++;
if (charsInLine >= maxCharsInLine && char.IsWhiteSpace(c))
{
builder.AppendLine();
charsInLine = 0;
}
}
return builder.ToString();
}
But this breaks when there's a short word, followed by a longer word. "foo howcomputerwork" with a max length of 16 doesn't break, but I want it to. One thought I has was looking forward to see where the next whitespace occurs, but I'm not sure whether that would result in the fewest lines possible.
Enjoy!
public static string SplitToLines(string text, char[] splitOnCharacters, int maxStringLength)
{
var sb = new StringBuilder();
var index = 0;
while (text.Length > index)
{
// start a new line, unless we've just started
if (index != 0)
sb.AppendLine();
// get the next substring, else the rest of the string if remainder is shorter than `maxStringLength`
var splitAt = index + maxStringLength <= text.Length
? text.Substring(index, maxStringLength).LastIndexOfAny(splitOnCharacters)
: text.Length - index;
// if can't find split location, take `maxStringLength` characters
splitAt = (splitAt == -1) ? maxStringLength : splitAt;
// add result to collection & increment index
sb.Append(text.Substring(index, splitAt).Trim());
index += splitAt;
}
return sb.ToString();
}
Note that splitOnCharacters and maxStringLength could be saved in user settings area of the app.
Check the contents of the character before writing to the string builder and or it with the current count:
public static string BreakLine(string text, int maxCharsInLine)
{
int charsInLine = 0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (char.IsWhiteSpace(c) || charsInLine >= maxCharsInLine)
{
builder.AppendLine();
charsInLine = 0;
}
else
{
builder.Append(c);
charsInLine++;
}
}
return builder.ToString();
}
update a code a bit, the #dead.rabit goes to loop sometime.
public static string SplitToLines(string text,char[] splitanyOf, int maxStringLength)
{
var sb = new System.Text.StringBuilder();
var index = 0;
var loop = 0;
while (text.Length > index)
{
// start a new line, unless we've just started
if (loop != 0)
{
sb.AppendLine();
}
// get the next substring, else the rest of the string if remainder is shorter than `maxStringLength`
var splitAt = 0;
if (index + maxStringLength <= text.Length)
{
splitAt = text.Substring(index, maxStringLength).LastIndexOfAny(splitanyOf);
}
else
{
splitAt = text.Length - index;
}
// if can't find split location, take `maxStringLength` characters
if (splitAt == -1 || splitAt == 0)
{
splitAt = text.IndexOfAny(splitanyOf, maxStringLength);
}
// add result to collection & increment index
sb.Append(text.Substring(index, splitAt).Trim());
if(text.Length > splitAt)
{
text = text.Substring(splitAt + 1).Trim();
}
else
{
text = string.Empty;
}
loop = loop + 1;
}
return sb.ToString();
}

Counting how many times a certain char appears in a string before any other char appears

I have many strings. Each string is prepended with at least 1 $. What is the best way to loop through the chars of each string to count how many $'s there are per string.
eg:
"$hello" - 1
"$$hello" - 2
"$$h$ello" - 2
You could use the Count method
var count = mystring.Count(x => x == '$')
int count = myString.TakeWhile(c => c == '$').Count();
And without LINQ
int count = 0;
while(count < myString.Length && myString[count] == '$') count++;
The simplest approach would be to use LINQ:
var count = text.TakeWhile(c => c == '$').Count();
There are certainly more efficient approaches, but that's probably the simplest.
You could do this, it doesn't require LINQ, but it's not the best way to do it(since you make split the whole string and put it in an array and just pick the length of it, you could better just do a while loop and check every character), but it works.
int count = test.Split('$').Length - 1;
var str ="hello";
str.Where(c => c == 'l').Count() // 2
int count = yourText.Length - yourText.TrimStart('$').Length;
int count = Regex.Matches(myString,"$").Count;
public static int GetHowManyTimeOccurenceCharInString(string text, char c)
{
int count = 0;
foreach(char ch in text)
{
if(ch.Equals(c))
{
count++;
}
}
return count;
}
just a simple answer:
public static int CountChars(string myString, char myChar)
{
int count = 0;
for (int i = 0; i < myString.Length; i++)
{
if (myString[i] == myChar) ++count;
}
return count;
}
Cheers! - Rick
One approach you could take is the following method:
// Counts how many of a certain character occurs in the given string
public static int CharCountInString(char chr, string str)
{
return str.Split(chr).Length-1;
}
As per the parameters this method returns the count of a specific character within a specific string.
This method works by splitting the string into an array by the specified character and then returning the length of that array -1.
//This code worked for me
class CountOfLettersOfString
{
static void Main()
{
Console.WriteLine("Enter string to check count of letters");
string name = Console.ReadLine();
//Method1
char[] testedalphabets = new char[26];
int[] letterCount = new int[26];
int countTestesd = 0;
Console.WriteLine($"Given String is:{name}");
for (int i = 0; i < name.Length - 1; i++)
{
int countChar = 1;
bool isCharTested = false;
for (int j = 0; j < testedalphabets.Length - 1; j++)
{
if (name[i] == testedalphabets[j])
{
isCharTested = true;
break;
}
}
if (!isCharTested)
{
testedalphabets[countTestesd] = name[i];
for (int k = i + 1; k < name.Length - 1; k++)
{
if (name[i] == name[k])
{
countChar++;
}
}
letterCount[countTestesd] = countChar;
countTestesd++;
}
else
{
continue;
}
}
for (int i = 0; i < testedalphabets.Length - 1; i++)
{
if (!char.IsLetter(testedalphabets[i]))
{
continue;
}
Console.WriteLine($"{testedalphabets[i]}-{letterCount[i]}");
}
//Method2
var g = from c in name.ToLower().ToCharArray() // make sure that L and l are the same eg
group c by c into m
select new { Key = m.Key, Count = m.Count() };
foreach (var item in g)
{
Console.WriteLine(string.Format("Character:{0} Appears {1} times", item.Key.ToString(), item.Count));
}
Console.ReadLine();
}
}
This is a similar Solution to find how many email addresses included in a string. This way is more efficient`
int count = 0;
foreach (char c in email.Trim())
if (c == '#') count++;

How to find substring from string without using indexof method in C#?

I want to find the position of a substring in a string if present without using any string method including indexof. I tried so much times but failed. Will anybody tell me how to do in C#? We can use .Length operator.
Sorry.. thought this would be a fun exercise for me, so...
Spoiler
class Program
{
static void Main(string[] args)
{
string str = "abcdefg";
string substr = "cde";
int index = IndexOf(str, substr);
Console.WriteLine(index);
Console.ReadLine();
}
private static int IndexOf(string str, string substr)
{
bool match;
for (int i = 0; i < str.Length - substr.Length + 1; ++i)
{
match = true;
for (int j = 0; j < substr.Length; ++j)
{
if (str[i + j] != substr[j])
{
match = false;
break;
}
}
if (match) return i;
}
return -1;
}
}
Assuming this is homework, my suggestion is to bear in mind that a string is an IEnumerable of chars. So you can loop through the characters in your string...
Since any homework that inspired the question is well past due, here's a stab at a reasonably performant answer.
Simply cycling through the larger string, and cycling through the substring comparing each character as one goes takes Θ((n-m+1) m) time where m is the length of the substring, and n the index where the smaller string is found, or if there is no match the length of the larger minus that of the smaller.
There are a few different algorithm that give better performance, which differ among themselves in terms of which cases they work best in. The Knuth-Morris-Pratt algorithm takes Θ(m) to set up and then Θ(n) time to find, because it first creates a table to know how far ahead it can jump on failing to find a match, and on balance this makes for a quicker search.
Consider that if we were looking for "ababcd" and we'd first found "abab…" (possible match so far), if the next character is c we still have a possible match. If it's a we don't have a match, but should jump forward two characters to start looking for a match starting from that. If it's anything else, we should jump ahead five characters and continue looking for there. Preparing the table to tell us how far to jump makes things much faster from then on:
public static int IndexOf(string haystack, string needle)
{
if(haystack == null || needle == null)
throw new ArgumentNullException();
if(needle.Length == 0)
return 0;//empty strings are everywhere!
if(needle.Length == 1)//can't beat just spinning through for it
{
char c = needle[0];
for(int idx = 0; idx != haystack.Length; ++idx)
if(haystack[idx] == c)
return idx;
return -1;
}
if (needle.Length == haystack.Length) return needle == haystack ? 0 : -1;
if (needle.Length < haystack.Length)
{
int m = 0;
int i = 0;
int[] T = KMPTable(needle);
while(m + i < haystack.Length)
{
if(needle[i] == haystack[m + i])
{
if(i == needle.Length - 1)
return m == haystack.Length ? -1 : m;//match -1 = failure to find conventional in .NET
++i;
}
else
{
m = m + i - T[i];
i = T[i] > -1 ? T[i] : 0;
}
}
}
return -1;
}
private static int[] KMPTable(string sought)
{
int[] table = new int[sought.Length];
int pos = 2;
int cnd = 0;
table[0] = -1;
table[1] = 0;
while(pos < table.Length)
if(sought[pos - 1] == sought[cnd])
table[pos++] = ++cnd;
else if(cnd > 0)
cnd = table[cnd];
else
table[pos++] = 0;
return table;
}
Try this:
internal bool SearchWord(string str, string searchKey)
{
int j = 0; bool result = false;
for (int i = 0; i < str.Length; i++)
{
if (searchKey[j] == str[i])
{
j++; //count++;
}
else { j = 0; }
if (j == searchKey.Length)
{
result = true;
break;
}
}
return result;
}
Try this:
public static string BetweenOf(string ActualStr, string StrFirst, string StrLast)
{
return ActualStr.Substring(ActualStr.IndexOf(StrFirst) + StrFirst.Length,
(ActualStr.Substring(ActualStr.IndexOf(StrFirst))).IndexOf(StrLast) + StrLast.Length);
}
string mainString = Console.ReadLine();
string subString = Console.ReadLine();
for (int i = 0; i <= mainString.Length - subString.Length; i++)
{
bool match = true;
for (int j = 0; j < subString.Length && mainString[i + j] != subString[j]; j++)
{
match = false;
}
if (match)
Console.WriteLine(i);
}
public static findindex(String str,String substr)
{
char a[]=str.toCharArray();
char b[]=substr.toCharArray();
int j=0,t=0;
for(int i=0;i<str.length()&&j<substr.length();i++)
{
if(a[i]==b[j])
{
t=i;
j++;
}
else
continue;
}
if(t==0)
return -1;
else
return t-substr.length()+1;
}//in java

Categories