Now I know how to count the number of characters in the entire input text, using the TextChanged
event, using charCount=input.Text.Length
.
Then, what should I do to find out how many characters are in the input text?
*Both characters (search words, text to be searched) will be entered in the text box.
Example
Input text → December is a busy month ahead of Christmas and New Year's Day.
Input search word → month
Results are 3 characters
c# wpf
For example:
string target="December is a busy month ahead of Christmas and New Year's Day.";
string find = "month";
int count = 0;
int index=target.IndexOf(find, StringComparison.Order);
while (0<=index)
{
count++;
index=target.IndexOf(find, index+1, StringComparison.Order);
}
// count = 3
Repeat looking for the string from the beginning, add count 1 to count, and look for the next string.
Total length of string - length of string with destination deleted = number of destination characters
str.Length-str.Replace(chara.ToString(), "").Length;
WPF provides a wealth of binding capabilities.
Implement IValueConverter
.MultiBinding
allows you to bind multiple values.You can bind the input text and the input search word.IMultiValueConverter
as the converter.Binding
has StringFormat
and can be formatted.Other people answered how to count characters, but you can also use the number that matches the regular expression.To sum up, define a CountConverter
implementing IMultiValueConverter
.
public class CountConverter:IMultiValueConverter{
static int Count (string input, string pattern)
=>Regex.Matches(input,Regex.Escape(pattern)) .Count;
public object Convert (object[] values, Type targetType, object parameter, CultureInfoculture)
=>Count(string) values[0], (string) values[1]);
public object [ ] ConvertBack (object value, Type [ ] targetTypes, object parameter, CultureInfoculture)
=>throw new NotImplementedException();
}
The XAML side has registered a converter in the resource dictionary.
<Window.Resources>
<local:CountConverter x:Key="CountConverter"/>
</ Window.Resources>
Then prepare and bind TextBox
and TextBlock
.
<TextBoxName="source"Text="December is a busy month ahead of Christmas and New Year's Day." HorizontalAlignment="Left" Height="23" Margin="28,29,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="300"/>
<TextBox Name="template" Text="Month" HorizontalAlignment="Left" Height="23" Margin="28,57,0,0"TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/gt;
<TextBlock HorizontalAlignment="Left" Margin="28,85,0,0"TextWrapping="Wrap" VerticalAlignment="Top">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource CountConverter}"StringFormat="Results are {0} characters">
<Binding ElementName="source"Path="Text"/>
<Binding ElementName="template" Path="Text"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Of course, it's a bind, so editing characters reflects results almost in real time.
© 2024 OneMinuteCode. All rights reserved.