How do I remove an X number of capital letters from a string? [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to remove an X number of capital letters from a string.
For example if I had the strings:
string Line1 = "NICEWEather";
and
string Line2 = "HAPpyhour";
How would I create a function that pulls out the 2 sets of Capital letters?

Try using regular expressions with \p{Lu} for a Unicode capital letter
using System.Text.RegularExpressions;
...
// Let's remove 2 or more consequent capital letters
int X = 2;
// English and Russian
string source = "NICEWEather - ХОРОшая ПОГОда - Keep It (HAPpyhour)";
// ather - шая да - Keep It (pyhour)
string result = Regex.Replace(source, #"\p{Lu}{" + X.ToString() + ",}", "");
Here we use \p{Lu}{2,} pattern: capital letter appeared X (2 in the code above) or more times.

To remove capital letter from string
string str = " NICEWEather";
Regex pattern = new Regex("[^a-z]");
string result = pattern.Replace(str, "");
Console.WriteLine(result );
output: ather
to remove capital letter if occurrences more than once in sequence order then try this
string str = " NICEWEather";
Regex pattern = new Regex(#"\p{Lu}{2,}");
string output = pattern.Replace(str, "");
Console.WriteLine(output);

Related

Splitting a string into characters, but keeping some together [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have this string: TF'E'
I want to split it to characters, but the '" character should join the character before it.
So it would look like this: T, F' and E'
You could use a regular expression to split the string at each position immediately before a new letter and an optional ':
var input = "TF'E'";
var output = Regex.Split(input, #"(?<!^)(?=\p{L}'?)");
output will now be a string array like ["T", "F'", "E'"]. The lookbehind (?<!^) ensure we never split at the start of the string, whereas the lookahead (?=\p{L}'?) describes one letter \p{L} followed by 0 or 1 '.
You can use a regex to capture "an uppercase character followed optionally by an apostrophe"
var mc = Regex.Matches(input, "(?<x>[A-Z]'?)");
foreach(Match m in mc)
Console.WriteLine(m.Groups["x"].Value);
If you don't like regex, you can use this method:
public static IEnumerable<string> Split(string input)
{
for(int i = 0; i < input.Length; i++)
{
if(i != (input.Length - 1) && input[i+1] == '\'')
{
yield return input[i].ToString() + input[i+1].ToString();
i++;
}
else
{
yield return input[i].ToString();
}
}
}
We loop through the input string. We check if there is a next character and if it is a '. If true, return the current character and the next character and increase the index by one. If false, just return the current character.
Online demo: https://dotnetfiddle.net/sPCftB

regex to remove digits, allow only lowercase letters, remove special characters [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Here is my code :
private void txtMot_KeyUp(object sender, KeyEventArgs e)
{
/* Clear message */
txtMessage.Clear();
Regex regex = new Regex(#"\d+");
Match match = regex.Match(txtMot.Text);
if (match.Success)
{
/* Text in red*/
txtMessage.Foreground = Brushes.Red;
/* Message text*/
txtMessage.Text = "Only letters";
}
}
I managed to remove all the digits.
I'm wondering now, how can I make it to :
Remove the digits.
Allow only lowercase letters.
Remove any kind of special characters(_+ù$é)
How can I do it please?
you can simply use the regex [a-z] and test with different set of data, as it accepts only the lowercase letters
public static void Main()
{
string test = "_+ù$é"; //change this to any set of test data
Regex regex = new Regex(#"[a-z]");
Match match = regex.Match(test);
if (match.Success)
{
Console.WriteLine("Matched");
}
else
Console.WriteLine("Not Matched");
}
dotNetFiddle
EDIT:
The above snippet would fail in a scenario where;
string test = "_+ù$é abc";
^ as this contains both the special letters and the lowercase, if you only want the lowercase letters to be accepted then;
replace this:
Regex regex = new Regex(#"[a-z]");
with this pattern:
Regex regex = new Regex(#"^([a-z]{1,25})$"); //this makes sure the string
// is only of lowercase
// letters and does not contain any digits
// or special chars
dotNetFiddle

For loop check if string only has 3 capital letters followed by 4 numbers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I input a string that has to start with three capital letters and ending with four digits (like so: "SJL1036") the program is just supposed to check if my input follows that model.
if i were to input "Sjl1036" og "SJL103" it would output that it is a false statement.
Try this regular expression. 3 uppercase, 4 numbers.
^[A-Z]{3}[0-9]{4}$
For example:
var value = "FSK2526";
if (Regex.IsMatch(value, #"^[A-Z]{3}[0-9]{4}$")) {
// it matches
}
Although you could do it with for loop, but you could simplify it further with regex like:
Regex regex = new Regex(#"^[A-Z]{3}.*[0-9]{4}$");
Match match = regex.Match("SJL1036");
if (match.Success)
{
Console.WriteLine(match.Value);
}
If this is the requirement:
A string that has to start with three capital letters and ending with
four digits
Probably the most efficient approach is using string methods:
bool valid = input.Length >= 7
&& input.Remove(3).All(Char.IsUpper) // or input.Substring(0, 3)
&& input.Substring(input.Length - 4).All(Char.IsDigit);
If the actual requirement is "3 capital letters followed by 4 numbers"(so 7 characters) you just need to change input.Length >= 7 to input.Length == 7.
A non-Regex option, You can use a bit of LINQ like:
string str = "SJL1036";
if (str.Length == 7 &&
str.Take(3).All(char.IsUpper)
&& str.Skip(3).All(char.IsDigit))
{
Console.WriteLine("valid");
}
else
{
Console.WriteLine("invalid");
}

How can I return the index of the second word in a string that can have multiple white spaces followed by one word followed by multiple white spaces? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
String str =" vol ABCD C XYZ";
I want to return the index of "A"
Note: There are multiple white spaces before all words including the first.
This will get the index of A in your original example (String str =" vol ABCD C XYZ";):
int indexOfABCD = str.IndexOf(str.Trim()[str.Trim().IndexOf(' ')+1]);
If you have something like String str = " vol ABCD C XYZ"; where there are multiple spaces:
string secondword = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1];
int indexOfAinABCD = str.IndexOf(secondword.First());
If you want to get the indices of all the letters in the second word:
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
EDIT:
This will fail if you have A anywhere else in the first word. You should get an exact match through Regex:
int indexOfAinABCD = Regex.Match(str, string.Format(#"\W{0}\W",secondword)).Index+1;
IEnumerable<int> fullindex = Enumerable.Range(indexOfAinABCD, secondword.Length);
So something like String str = " vABCDol ABCD C XYZ"; won't be an issue

How to find the capital substring of a string? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to find the capitalized portion of a string, to then insert two characters that represent the Double Capital sign in the Braille language. My intention for doing this is to design a translator that can translate from regular text to Braille.
I'll give an example belo.
English String: My variable is of type IEnumerable.
Braille: ,My variable is of type ,,IE-numberable.
I also want the dash in IE-numerable to only break words that have upper and lower case, but not in front of punctuation marks, white spaces, numbers or other symbols.
Thanks a lot in advance for your answers.
I had never heard of a "Double Capital" sign, so I read up on it here. From what I can tell, this should suit your needs.
You can use this to find any sequence of two or more uppercase (majuscule) Latin letters or hyphens in your string:
var matches = Regex.Matches(input, "[A-Z-]{2,}");
You can use this to insert the double-capital sign:
var result = Regex.Replace(input, "[A-Z-]{2,}", ",,$0");
For example:
var input = "this is a TEST";
var result = Regex.Replace(input, "[A-Z-]{2,}", ",,$0"); // this is a ,,TEST
You can use this to hand single and double capitals:
var input = "McGRAW-HILL";
var result = Regex.Replace(input, "[A-Z-]([A-Z-]+)?",
m => (m.Groups[1].Success ? ",," : ",") + m.Value); // ,Mc,,GRAW-HILL
You can find them with a simple regex:
using System.Text.RegularExpressions;
// ..snip..
Regex r = new Regex("[A-Z]"); // This will capture only upper case characters
Match m = r.Match(input, 0);
The variable m of type System.Text.RegularExpressions.Match will contain a collection of captures. If only the first match matters, you can check its Index property directly.
Now you can insert the characters you want in that position, using String.Insert:
input = input.Insert(m.Index, doubleCapitalSign);
this code can solve your problema
string x = "abcdEFghijkl";
string capitalized = string.Empty;
for (int i = 0; i < x.Length; i++)
{
if (x[i].ToString() == x[i].ToString().ToUpper())
capitalized += x[i];
}
Have you tried using the method Char.IsUpper method
http://msdn.microsoft.com/en-us/library/9s91f3by.aspx
This is another similar question that uses that method to solve a similar problem
Get the Index of Upper Case letter from a String
If you just want to find the first index of an uppercase letter:
var firstUpperCharIndex = text // <-- a string
.Select((chr, index) => new { chr, index })
.FirstOrDefault(x => Char.IsUpper(x.chr));
if (firstUpperCharIndex != null)
{
text = text.Insert(firstUpperCharIndex.index, ",,");
}
Not sure if this is what you are going for?
var inputString = string.Empty; //Your input string here
var output = new StringBuilder();
foreach (var c in inputString.ToCharArray())
{
if (char.IsUpper(c))
{
output.AppendFormat("_{0}_", c);
}
else
{
output.Append(c);
}
}
This will loop through each character in the inputString if the characater is upper it inserts a _ before and after (replace that with your desired braille characters) otherwise appends the character to the output.

Categories