I want to set the limit min. 5 characters per line and
I want to show message if multiline textbox have less than 5 chars. line.
Here is my code.
string[] temp = Regex.Split(KeywordList.Text, "\r\n");
for (int i = 0; i < temp.Length; i++)
{
if (temp[i].Length <= 4) //check characters limit
{
Response.Write("Please enter min 5 characters per line");
}
else
{
Response.Write("success");
}
}
My textbox contains min. 5 characters in few lines but above code show "success".
Can anyone help me to detect less than 5 characters row.
Thanks in advance, sorry for my bad English.
I suggest using Linq: Split the initial string (please, do not put magic values like "\r\n", but Environment.NewLine) and check if Any item is 4 characters or less:
if (KeywordList
.Text
.Split(new string[] {Environment.NewLine}, StringSplitOptions.None)
.Any(item => item.Length <= 4))
Response.Write("Please enter min 5 characters per line");
else
Response.Write("success");
In your current code Regex.Split is an overshoot (String.Split is enough), and it seems that you should add break after Response.Write("Please enter min 5 characters per line"); line:
...
if (temp[i].Length <= 4) //check characters limit
{
Response.Write("Please enter min 5 characters per line");
break; // <- we have an error, no need to check more lines
}
...
Edit: If you are not sure in delimiters (they can be \n - Unix, \r\n - Windows, \n\r - Mac etc.) you can try several ones in one call
if (KeywordList
.Text
.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries)
.Any(item => item.Length <= 4))
Response.Write("Please enter min 5 characters per line");
else
Response.Write("success");
However, we have to eliminate empty items: for "a\r\n\b" we want ["a", "b"], not ["a", "", "b"]
Related
Need to get three strings from the below mentioned string, need the possible solution in C# and ASP.NET:
"componentStatusId==2|3,screeningOwnerId>0"
I need to get '2','3' and '0' using a regular expression in C#
If all you want is the numbers from a string then you could use the regex in this code:
string re = "(?:\\b(\\d+)\\b[^\\d]*)+";
Regex regex = new Regex(re);
string input = "componentStatusId==2|3,screeningOwnerId>0";
MatchCollection matches = regex.Matches(input);
for (int ii = 0; ii < matches.Count; ii++)
{
Console.WriteLine("Match[{0}] // of 0..{1}:", ii, matches.Count - 1);
DisplayMatchResults(matches[ii]);
}
Function DisplayMatchResults is taken from this Stack Overflow answer.
The Console output from the above is:
Match[0] // of 0..0:
Match has 1 captures
Group 0 has 1 captures '2|3,screeningOwnerId>0'
Capture 0 '2|3,screeningOwnerId>0'
Group 1 has 3 captures '0'
Capture 0 '2'
Capture 1 '3'
Capture 2 '0'
match.Groups[0].Value == "2|3,screeningOwnerId>0"
match.Groups[1].Value == "0"
match.Groups[0].Captures[0].Value == "2|3,screeningOwnerId>0"
match.Groups[1].Captures[0].Value == "2"
match.Groups[1].Captures[1].Value == "3"
match.Groups[1].Captures[2].Value == "0"
Hence the numbers can be seen in match.Groups[1].Captures[...].
Another possibility is to use Regex.Split where the pattern is "non digits". The results from the code below will need post processing to remove empty strings. Note that Regex.Split does not have the StringSplitOptions.RemoveEmptyEntries of the string Split method.
string input = "componentStatusId==2|3,screeningOwnerId>0";
string[] numbers = Regex.Split(input, "[^\\d]+");
for (int ii = 0; ii < numbers.Length; ii++)
{
Console.WriteLine("{0}: '{1}'", ii, numbers[ii]);
}
The output from this is:
0: ''
1: '2'
2: '34'
3: '0'
Use following regex and capture your values from group 1, 2 and 3.
componentStatusId==(\d+)\|(\d+),screeningOwnerId>(\d+)
Demo
For generalizing componentStatusId and screeningOwnerId with any string, you can use \w+ in the regex and make it more general.
\w+==(\d+)\|(\d+),\w+>(\d+)
Updated Demo
I have a 9 character string I am trying to provide multiple checks on. I want to first check if the first 1 - 7 characters are numbers and then say for example the first 3 characters are numbers how would I check the 5th character for a letter range of G through T.
I am using c# and have tried this so far...
string checkString = "123H56789";
Regex charactorSet = new Regex("[G-T]");
Match matchSetOne = charactorSetOne.Match(checkString, 3);
if (Char.IsNumber(checkString[0]) && Char.IsNumber(checkString[1]) && Char.IsNumber(checkString[2]))
{
if (matchSetOne.Success)
{
Console.WriteLine("3th char is a letter");
}
}
But am not sure if this is the best way to handle the validations.
UPDATE:
The digits can be 0 - 9, but can concatenate from one number to seven. Like this "12345T789" or "1R3456789" etc.
It'a easy with LINQ:
check if the first 1 - 7 characters are numbers :
var condition1 = input.Take(7).All(c => Char.IsDigit(c));
check the 5th character for a letter range of G through T
var condition2 = input.ElementAt(4) >= 'G' && input.ElementAt(4) <= 'T';
As it is, both conditions can't be true at the same time (if the first 7 chars are digits, then the 5th char can't be a letter).
How to format a number such that first 6 digits and last 4 digits are not hidden
such that 111111111111111 looks like 111111****1111
You can also use LINQ, substituting chars with indexes more than 5 and less than number.Length - 4 with *:
string number = "111111111111111";
string res = new string(number.Select((c, index) => { return (index <= 5 || index >= number.Length - 4) ? c : '*'; }).ToArray());
Console.WriteLine(res); // 111111*****1111
One simple way to do this is to slit the input..
int number = 111111111111111;
string firstsix = number.ToString().Substring(0,6) //gets the first 6 digits
string middlefour = number.ToString().Substring(6,4) //gets the next 4
string rest = number.ToString().Substring(10, number.ToString().Lenght) //gets the rest
string combined = firstsix + "****" +rest;
You need to use \G anchor in-order to do a continuous string match.
string result = Regex.Replace(str, #"(?:^(.{6})|\G).(?=.{4})", "$1*");
DEMO
IDEONE
I have a textbox and i want that it should have only 21 characters at max and they should be displayed in 3 lines(7 characters in each). As the user is typing when he types the 7th character i want the focus to be shifted to next line. I have already tried the following code
int textLength = a.Text.Length;
if (textLength % 8 == 0)
{
a.Text += "\n";
a.SelectionStart = a.Text.Length - 1;
}
It does not work .
Thanks for the help.
I am working through Joyce Farrell's Visual C#2012 on my own (this is not a homework assignment). I have been stuck on this for the past two days, and have yet to find an answer that I understand. I am looking for a simple program - nothing fancy as I probably haven't read that chapter yet. :-) The problem that I am having is when I am trying to show '' for a non-guessed or incorrectly guessed letter. If I assign '' it looks good for the first letter, but when the user enters a second guess, it changes the second guess to a '?'. Why is that? Any help would be really appreciated. Thank you.
static void Main(string[] args)
{
string[] mysteryWordList = { "green", "snowflake", "tree", "joy", "red", "gift", "frozen", "merry" };
string mysteryWord; // hidden word
char[] mysteryWordArray;
char letterGuessed;
char[] guessWordArray;
Random ranNumberGenerator = new Random(); // generate a random number, at least 0 but < 8
int randomNumber = ranNumberGenerator.Next(0, 8);
mysteryWord = mysteryWordList[randomNumber]; // select a word from list using random number
Console.WriteLine("The Mystery word is: " + mysteryWord); // print word for my validation
mysteryWordArray = mysteryWord.ToArray(); // put mystery word into array to compare against guessWord array
Console.Write("MysterywordArray is: ");
Console.WriteLine(mysteryWordArray);
guessWordArray = new char[mysteryWord.Length]; // assign length to user guess array
// write mystery word in *'s
for (int x = 0; x < mysteryWord.Length; ++x)
Console.Write("*");
//guessWordArray[x] += '%'; adds value and then does not work...
Console.WriteLine();
while (guessWordArray != mysteryWordArray)
{
Console.Write("\nPlease guess a letter: ");
letterGuessed = Convert.ToChar(Console.ReadLine());
for (int x = 0; x < mysteryWord.Length; ++x)// go through each letter in mystery word
{
if (letterGuessed == mysteryWordArray[x]) // if match do this
{
Console.WriteLine("Yes, the letter {0} is in the mystery word!", letterGuessed);
guessWordArray[x] += letterGuessed;
}
if (letterGuessed != mysteryWordArray[x] && guessWordArray[x] == default(char)) // if match do this
guessWordArray[x] += '*';
}
Console.Write("Mystery Word: ");
Console.WriteLine(guessWordArray);
}
}
The command guessWordArray[x] += letterGuessed; is wrong. It dosent add the letter to the array it actualy changes the Xth element in the array. For example if guesswordArray contains { 'a', 'b', 'c' }
guesswordArray[0] += 'a' translates to guessWordArray[2] = 'a' + 'a'. Character addition is done by converting a character to the ascii code then the result is converted to a character. That means 'a'== 97 'a'+'a' == 194' Then 194 is converted back to a weird character from the ascii table.
This two lines :
guessWordArray[x] += letterGuessed;
....
guessWordArray[x] += '*';
should be like this instead :
guessWordArray[x] = letterGuessed;
....
guessWordArray[x] = '*';
By this += operator, you are appending the char from user input to existing char saved in the array. That will produce special character which which won't be displayed well in console (that's why you saw sort of ? char). I think you need to just assign the input char and replace existing char by using = instead of +=
Characters are essentially integers in their most basic form. When you are attempting to add subsequent letters to your array you are using += which is adding characters together. The initial character '*' is ASCII code 42, so what's happening is when you select a new letter ('g' for example in "gift") you are adding 103 to to that 42, and the ASCII character with the value 145 is being stored in the array. That value is unable to be displayed properly by the console. You need to just use the assignment operator since you want to write the new character to the array at the current index.
guessWordArray[x] = letterGuessed;
guessWordArray[x] = '*';