I need to count all vowels and replace it with the letter x, in a textbox. I managed to do the counting part and here's the code, but i'm having problem with replacing all vowels in the textbox with the letter x. Can someone help me?
int total = 0;
string sentence = textBox1.Text.ToLower();
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'y'};
{
total++;
}
total = sentence.Count(c => vowels.Contains(c));
MessageBox.Show("There are " + total++ " vowels";
for (int i = 0; i < sentence.Length; i++)
EDIT 1:
Thank you all for helping. For some reason the vowels in my textbox doesnt change!!! It does the counting but no replacement of the letter x. I've tried all the solutions here, but still nothing happens to my the vowels in the textbox.
foreach(char vowel in vowels)
sentence = sentence.Replace(vowel, 'x');
For some reason the vowels in my textbox doesnt change!!! It does the
counting but no replacement of the letter x. I've tried all the
solutions here, but still nothing happens to my the vowels in the
textbox.
The textbox and the string are not linked with each other. So if you change the string you won't change the TextBox.Text. You have to re-assign the new value:
textBox1.Text = sentence; // after you have used Replace like shown above
You can use Linq:
sentence = string.Concat(sentence.Select(c => vowels.Contains(c) ? 'x' : c));
Just a simple regex:
var r = new Regex("[aeiouy]");
sentence = r.Replace(sentence, "x");
EDIT: As strings are immutable changes to sentence are not reflected in your textbox, so you have to re-assign its value:
textBox1.Text = sentence;
Try to use a ForEach Linq-Expression and string.Replace method:
vowels.ToList().ForEach(vowel => sentence = sentence.Replace(vowel, 'x'));
EDIT 1:
You could also try a for-loop as you also tried in your question:
for (int i = 0; i < sentence.Length; i++) {
if(vowels.Contains((char)sentence[i])) {
sentence[i] = 'x';
}
}
EDIT 2:
To write the value of sentence back to the TextBox add the following:
textBox1.Text = sentence;
Why not maybe simply try with a regular expresion, as the colleague above has already suggested?
Something like:
string text = "Here comes some text";
string vowels = #"([aeiou])";
Regex regex = new Regex(vowels);
Match match = regex.Match(text);
and then maybe continue your logic with some collection and a foreach cycle()in wich you do the replacing with a char/string "x".
Related
I'm trying to get this to write every word from input in a new line, even if there are more spaces between words, but I can't figure out what is wrong with this.
string phrase = Console.ReadLine();
string currentWord = "";
for (int i = 0; i < phrase.Length; i++)
{
if (phrase[i] == ' ')
Console.WriteLine(currentWord);
currentWord = "";
while (phrase[i] == ' ')
i++;
if (phrase[i] != ' ')
currentWord += phrase[i];
}
Console.WriteLine(currentWord);
I'm only getting the last letter from every word. Any help, please?
And if let's say, I want to print out the nth word of phrase(n is from input), how can I do that?
Since you are not using braces in your if statement, this code gets executed in every iteration:
currentWord = "";
So you reset the value of currentWord.
You could simply use Split method with StringSplitOptions.RemoveEmptyEntries, no need to reinvent the wheel:
var words = phrase.Split(new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Thats what happens when you don’t use curly braces in if and while bodies...
Write them both with braces and spot the difference with your current code.
I would probably do it this way..
First add this reference:
using System.Text.RegularExpressions;
Then you can use a simple regex to split your string into words and a foreach loop to display the words:
var phrase = Console.ReadLine();
var words = Regex.Split(phrase, #"\s+");
foreach(var word in words)
Console.WriteLine(word)
This is also a lot cleaner compared to the code you have, which makes it a lot easier to read, understand and maintain.
You can replace char with Replace method
Follow code:
Console.ReadLine().Replace(" ","");
Quick little question...
I need to count the length of a string, but WITHOUT the spaces inside of it.
E.g. for a string like "I am Bob", string.Length would return 8 (6 letters + 2 spaces).
I need a method, or something, to give me the length (or number of) just the letters (6 in the case of "I am Bob")
I have tried the following
s.Replace (" ", "");
s.Replace (" ", null);
s.Replace (" ", string.empty);
to try and get "IamBob", which I did, but it didn't solve my problem because it still counted "" as a character.
Any help?
This returns the number of non-whitespace characters:
"I am Bob".Count(c => !Char.IsWhiteSpace(c));
Demo
Char.IsWhiteSpace:
White space characters are the following Unicode characters:
Members of the SpaceSeparator category, which includes the characters SPACE (U+0020), OGHAM SPACE MARK (U+1680), MONGOLIAN VOWEL SEPARATOR (U+180E), EN QUAD (U+2000), EM QUAD (U+2001), EN SPACE (U+2002), EM SPACE (U+2003), THREE-PER-EM SPACE (U+2004), FOUR-PER-EM SPACE (U+2005), SIX-PER-EM SPACE (U+2006), FIGURE SPACE (U+2007), PUNCTUATION SPACE (U+2008), THIN SPACE (U+2009), HAIR SPACE (U+200A), NARROW NO-BREAK SPACE (U+202F), MEDIUM MATHEMATICAL SPACE (U+205F), and IDEOGRAPHIC SPACE (U+3000).
Members of the LineSeparator category, which consists solely of the LINE SEPARATOR character (U+2028).
Members of the ParagraphSeparator category, which consists solely of the PARAGRAPH SEPARATOR character (U+2029).
The characters CHARACTER TABULATION (U+0009), LINE FEED (U+000A), LINE TABULATION (U+000B), FORM FEED (U+000C), CARRIAGE RETURN (U+000D), NEXT LINE (U+0085), and NO-BREAK SPACE (U+00A0).
No. It doesn't.
string s = "I am Bob";
Console.WriteLine(s.Replace(" ", "").Length); // 6
Console.WriteLine(s.Replace(" ", null).Length); //6
Console.WriteLine(s.Replace(" ", string.Empty).Length); //6
Here is a DEMO.
But what are whitespace characters?
http://en.wikipedia.org/wiki/Whitespace_character
You probably forgot to reassign the result of Replace. Try this:
string s = "I am bob";
Console.WriteLine(s.Length); // 8
s = s.Replace(" ", "");
Console.WriteLine(s.Length); // 6
A pretty simple way is to write an extension method that will do just that- count the characters without the white spaces. Here's the code:
public static class MyExtension
{
public static int CharCountWithoutSpaces(this string str)
{
string[] arr = str.Split(' ');
string allChars = "";
foreach (string s in arr)
{
allChars += s;
}
int length = allChars.Length;
return length;
}
}
To execute, simply call the method on the string:
string yourString = "I am Bob";
int count = yourString.CharCountWithoutSpaces();
Console.WriteLine(count); //=6
Alternatively, you can split the string an way you want if you don't want to include say, periods or commas:
string[] arr = str.Split('.');
or:
string[] arr = str.Split(',');
this is fastest way:
var spaceCount = 0;
for (var i 0; i < #string.Lenght; i++)
{
if (#string[i]==" ") spaceCount++;
}
var res = #string.Lenght-spaceCount;
Your problem is probably related to Replace() method not actually changing the string, rather returning the replaced value;
string withSpaces = "I am Bob";
string withoutSpaces = withSpaces.Replace(" ","");
Console.WriteLine(withSpaces);
Console.WriteLine(withoutSpaces);
Console.WriteLine(withSpaces.Length);
Console.WriteLine(withoutSpaces.Length);
//output
//I am Bob
//IamBob
//8
//6
You can use a combination of Length and Count functions on the string object. Here is a simple example.
string sText = "This is great text";
int nSpaces = sText.Length - sText.Count(Char.IsWhiteSpace);
This will count single or multiple (consistent) spaces accurately.
Hope it helps.
I need to get all numbers from a string like this:
"156234 something 567345 another thing 45789 anything"
The result should be a collection of numbers having:
156234, 567345, 45789
I tried #"\d+", but it will only give me 156234.
EDIT: The numbers are integers, however they can also occur like this "156234 something 567345 another thing 45789 anything2345". In this case I only need the integers i.e 156234, 567345, 45789 and not 156234, 567345, 45789,2345.
Also the integers which i dont want will always be preceed with a text for ex:anything2345.
Everything is ok with your regex, you just need to come through all the matches.
Regex regex = new Regex(#"\d+");
foreach (Match match in regex.Matches("156234 something 567345 another thing 45789 anything"))
{
Console.WriteLine(match.Value);
}
You want to split on the characters, not the digits. Use the capital D
string[] myStrings = Regex.Split(sentence, #"\D+");
Source
If 2345 should not be matched in your revised sample string (156234 something 567345 another thing 45789 anything2345), you could use Dima's solution but with the regex:
\b\d+\b
This assures that the number is surrounded by word boundaries.
This'z in java. You don't actually need a Regex.. just a normal replaceAll should do the trick for you! : For ex : You can strip off the Non-Digits, and then split and calculate the sum.
public static int getSumOfNumbers(String s) {
int sum = 0;
String x = s.replaceAll("\\D+", " ");
String[] a = x.split(" ");
for(int i = 0; i < a.length; i++)
sum += Integer.parseInt(a[i]);
System.out.println(x + " : and sum is : "+sum);
return sum;
}
I want to find number of letter "a" in only first sentence. The code below finds "a" in all sentences, but I want in only first sentence.
static void Main(string[] args)
{
string text; int k = 0;
text = "bla bla bla. something second. maybe last sentence.";
foreach (char a in text)
{
char b = 'a';
if (b == a)
{
k += 1;
}
}
Console.WriteLine("number of a in first sentence is " + k);
Console.ReadKey();
}
This will split the string into an array seperated by '.', then counts the number of 'a' char's in the first element of the array (the first sentence).
var count = Text.Split(new[] { '.', '!', '?', })[0].Count(c => c == 'a');
This example assumes a sentence is separated by a ., ? or !. If you have a decimal number in your string (e.g. 123.456), that will count as a sentence break. Breaking up a string into accurate sentences is a fairly complex exercise.
This is perhaps more verbose than what you were looking for, but hopefully it'll breed understanding as you read through it.
public static void Main()
{
//Make an array of the possible sentence enders. Doing this pattern lets us easily update
// the code later if it becomes necessary, or allows us easily to move this to an input
// parameter
string[] SentenceEnders = new string[] {"$", #"\.", #"\?", #"\!" /* Add Any Others */};
string WhatToFind = "a"; //What are we looking for? Regular Expressions Will Work Too!!!
string SentenceToCheck = "This, but not to exclude any others, is a sample."; //First example
string MultipleSentencesToCheck = #"
Is this a sentence
that breaks up
among multiple lines?
Yes!
It also has
more than one
sentence.
"; //Second Example
//This will split the input on all the enders put together(by way of joining them in [] inside a regular
// expression.
string[] SplitSentences = Regex.Split(SentenceToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase);
//SplitSentences is an array, with sentences on each index. The first index is the first sentence
string FirstSentence = SplitSentences[0];
//Now, split that single sentence on our matching pattern for what we should be counting
string[] SubSplitSentence = Regex.Split(FirstSentence, WhatToFind, RegexOptions.IgnoreCase);
//Now that it's split, it's split a number of times that matches how many matches we found, plus one
// (The "Left over" is the +1
int HowMany = SubSplitSentence.Length - 1;
System.Console.WriteLine(string.Format("We found, in the first sentence, {0} '{1}'.", HowMany, WhatToFind));
//Do all this again for the second example. Note that ideally, this would be in a separate function
// and you wouldn't be writing code twice, but I wanted you to see it without all the comments so you can
// compare and contrast
SplitSentences = Regex.Split(MultipleSentencesToCheck, "[" + String.Join("", SentenceEnders) + "]", RegexOptions.IgnoreCase | RegexOptions.Singleline);
SubSplitSentence = Regex.Split(SplitSentences[0], WhatToFind, RegexOptions.IgnoreCase | RegexOptions.Singleline);
HowMany = SubSplitSentence.Length - 1;
System.Console.WriteLine(string.Format("We found, in the second sentence, {0} '{1}'.", HowMany, WhatToFind));
}
Here is the output:
We found, in the first sentence, 3 'a'.
We found, in the second sentence, 4 'a'.
You didn't define "sentence", but if we assume it's always terminated by a period (.), just add this inside the loop:
if (a == '.') {
break;
}
Expand from this to support other sentence delimiters.
Simply "break" the foreach(...) loop when you encounter a "." (period)
Well, assuming you define a sentence as being ended with a '.''
Use String.IndexOf() to find the position of the first '.'. After that, searchin a SubString instead of the entire string.
find the place of the '.' in the text ( you can use split )
count the 'a' in the text from the place 0 to instance of the '.'
string SentenceToCheck = "Hi, I can wonder this situation where I can do best";
//Here I am giving several way to find this
//Using Regular Experession
int HowMany = Regex.Split(SentenceToCheck, "a", RegexOptions.IgnoreCase).Length - 1;
int i = Regex.Matches(SentenceToCheck, "a").Count;
// Simple way
int Count = SentenceToCheck.Length - SentenceToCheck.Replace("a", "").Length;
//Linq
var _lamdaCount = SentenceToCheck.ToCharArray().Where(t => t.ToString() != string.Empty)
.Select(t => t.ToString().ToUpper().Equals("A")).Count();
var _linqAIEnumareable = from _char in SentenceToCheck.ToCharArray()
where !String.IsNullOrEmpty(_char.ToString())
&& _char.ToString().ToUpper().Equals("A")
select _char;
int a =linqAIEnumareable.Count;
var _linqCount = from g in SentenceToCheck.ToCharArray()
where g.ToString().Equals("a")
select g;
int a = _linqCount.Count();
I'm trying to find an efficient way to take an input string and capitalize the first letter after every punctuation mark (. : ? !) which is followed by a white space.
Input:
"I ate something. but I didn't:
instead, no. what do you think? i
think not! excuse me.moi"
Output:
"I ate something. But I didn't:
Instead, no. What do you think? I
think not! Excuse me.moi"
The obvious would be to split it and then capitalize the first char of every group, then concatenate everything. But it's uber ugly. What's the best way to do this? (I'm thinking Regex.Replace using a MatchEvaluator that capitalizes the first letter but would like to get more ideas)
Thanks!
Fast and easy:
static class Ext
{
public static string CapitalizeAfter(this string s, IEnumerable<char> chars)
{
var charsHash = new HashSet<char>(chars);
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.Length - 2; i++)
{
if (charsHash.Contains(sb[i]) && sb[i + 1] == ' ')
sb[i + 2] = char.ToUpper(sb[i + 2]);
}
return sb.ToString();
}
}
Usage:
string capitalized = s.CapitalizeAfter(new[] { '.', ':', '?', '!' });
Try this:
string expression = #"[\.\?\!,]\s+([a-z])";
string input = "I ate something. but I didn't: instead, no. what do you think? i think not! excuse me.moi";
char[] charArray = input.ToCharArray();
foreach (Match match in Regex.Matches(input, expression,RegexOptions.Singleline))
{
charArray[match.Groups[1].Index] = Char.ToUpper(charArray[match.Groups[1].Index]);
}
string output = new string(charArray);
// "I ate something. But I didn't: instead, No. What do you think? I think not! Excuse me.moi"
I use an extension method.
public static string CorrectTextCasing(this string text)
{
// /[.:?!]\\s[a-z]/ matches letters following a space and punctuation,
// /^(?:\\s+)?[a-z]/ matches the first letter in a string (with optional leading spaces)
Regex regexCasing = new Regex("(?:[.:?!]\\s[a-z]|^(?:\\s+)?[a-z])", RegexOptions.Multiline);
// First ensure all characters are lower case.
// (In my case it comes all in caps; this line may be omitted depending upon your needs)
text = text.ToLower();
// Capitalize each match in the regular expression, using a lambda expression
text = regexCasing.Replace(text, s => (s.Value.ToUpper));
// Return the new string.
return text;
}
Then I can do the following:
string mangled = "i'm A little teapot, short AND stout. here IS my Handle.";
string corrected = s.CorrectTextCasing();
// returns "I'm a little teapot, short and stout. Here is my handle."
Using the Regex / MatchEvaluator route, you could match on
"[.:?!]\s[a-z]"
and capitalize the entire match.
Where the text variable contains the string
string text = "I ate something. but I didn't: instead, no. what do you think? i think not! excuse me.moi";
string[] punctuators = { "?", "!", ",", "-", ":", ";", "." };
for (int i = 0; i< 7;i++)
{
int pos = text.IndexOf(punctuators[i]);
while(pos!=-1)
{
text = text.Insert(pos+2, char.ToUpper(text[pos + 2]).ToString());
text = text.Remove(pos + 3, 1);
pos = text.IndexOf(punctuators[i],pos+1);
}
}