Trim spaces from end of a NSString - nsstring

I need to remove spaces from the end of a string. How can I do that?
Example: if string is "Hello " it must become "Hello"

Taken from this answer here: https://stackoverflow.com/a/5691567/251012
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return #"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}

Another solution involves creating mutable string:
//make mutable string
NSMutableString *stringToTrim = [#" i needz trim " mutableCopy];
//pass it by reference to CFStringTrimSpace
CFStringTrimWhiteSpace((__bridge CFMutableStringRef) stringToTrim);
//stringToTrim is now "i needz trim"

Here you go...
- (NSString *)removeEndSpaceFrom:(NSString *)strtoremove{
NSUInteger location = 0;
unichar charBuffer[[strtoremove length]];
[strtoremove getCharacters:charBuffer];
int i = 0;
for(i = [strtoremove length]; i >0; i--) {
NSCharacterSet* charSet = [NSCharacterSet whitespaceCharacterSet];
if(![charSet characterIsMember:charBuffer[i - 1]]) {
break;
}
}
return [strtoremove substringWithRange:NSMakeRange(location, i - location)];
}
So now just call it. Supposing you have a string that has spaces on the front and spaces on the end and you just want to remove the spaces on the end, you can call it like this:
NSString *oneTwoThree = #" TestString ";
NSString *resultString;
resultString = [self removeEndSpaceFrom:oneTwoThree];
resultString will then have no spaces at the end.

NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//for remove whitespace and new line character
NSString *trimmedString = [string stringByTrimmingCharactersInSet:
[NSCharacterSet punctuationCharacterSet]];
//for remove characters in punctuation category
There are many other CharacterSets. Check it yourself as per your requirement.

To remove whitespace from only the beginning and end of a string in Swift:
Swift 3
string.trimmingCharacters(in: .whitespacesAndNewlines)
Previous Swift Versions
string.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()))

Swift version
Only trims spaces at the end of the String:
private func removingSpacesAtTheEndOfAString(var str: String) -> String {
var i: Int = countElements(str) - 1, j: Int = i
while(i >= 0 && str[advance(str.startIndex, i)] == " ") {
--i
}
return str.substringWithRange(Range<String.Index>(start: str.startIndex, end: advance(str.endIndex, -(j - i))))
}
Trims spaces on both sides of the String:
var str: String = " Yolo "
var trimmedStr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

This will remove only the trailing characters of your choice.
func trimRight(theString: String, charSet: NSCharacterSet) -> String {
var newString = theString
while String(newString.characters.last).rangeOfCharacterFromSet(charSet) != nil {
newString = String(newString.characters.dropLast())
}
return newString
}

In Swift
To trim space & newline from both side of the String:
var url: String = "\n http://example.com/xyz.mp4 "
var trimmedUrl: String = url.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

A simple solution to only trim one end instead of both ends in Objective-C:
#implementation NSString (category)
/// trims the characters at the end
- (NSString *)stringByTrimmingSuffixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = self.length;
while (i > 0 && [characterSet characterIsMember:[self characterAtIndex:i - 1]]) {
i--;
}
return [self substringToIndex:i];
}
#end
And a symmetrical utility for trimming the beginning only:
#implementation NSString (category)
/// trims the characters at the beginning
- (NSString *)stringByTrimmingPrefixCharactersInSet:(NSCharacterSet *)characterSet {
NSUInteger i = 0;
while (i < self.length && [characterSet characterIsMember:[self characterAtIndex:i]]) {
i++;
}
return [self substringFromIndex:i];
}
#end

To trim all trailing whitespace characters (I'm guessing that is actually your intent), the following is a pretty clean & concise way to do it.
Swift 5:
let trimmedString = string.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
Objective-C:
NSString *trimmedString = [string stringByReplacingOccurrencesOfString:#"\\s+$" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
One line, with a dash of regex.

The solution is described here: How to remove whitespace from right end of NSString?
Add the following categories to NSString:
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return #"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}
- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
return [self stringByTrimmingTrailingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
And you use it as such:
[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]

I came up with this function, which basically behaves similarly to one in the answer by Alex:
-(NSString*)trimLastSpace:(NSString*)str{
int i = str.length - 1;
for (; i >= 0 && [str characterAtIndex:i] == ' '; i--);
return [str substringToIndex:i + 1];
}
whitespaceCharacterSet besides space itself includes also tab character, which in my case could not appear. So i guess a plain comparison could suffice.

let string = " Test Trimmed String "
For Removing white Space and New line use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespacesAndNewlines)
For Removing only Spaces from string use below code :-
let str_trimmed = yourString.trimmingCharacters(in: .whitespaces)

NSString* NSStringWithoutSpace(NSString* string)
{
return [string stringByReplacingOccurrencesOfString:#" " withString:#""];
}

Related

Adding Firebase data, dots and forward slashes

I try to use firebase db,
I found very important restrictions, which are not described in firebase help or FAQ.
First problem is that symbol: dot '.' prohibited in keys,
i.e. firebase reject (with unknown reason) next:
nameRef.child('Henry.Morgan#caribbean.sea').set('Pirat');
Second problem with forward slashes in your keys '/',
when you try to add key like this
{'02/10/2013': true}
In firebase you can see:
'02': {
'10': {
'2013': true
}
}
Have you got any ideas how to solve it (automatically)?
May be set some flag that it is string key with all symbols?
Of course, I can parse/restore data every time before write and after read, but...
By the way '.' '/' - all restricted symbols for firebase ?
The reason that adding a child 02/10/2013 creates a structure in Firebase is because the forward slashes are resulting in the creation of a new level.
So the line I assume you are using something similar to: firebaseRef.child('02/10/2013').set(true) is equivalent to firebaseRef.child('02').child('10').child('2013').set(true).
To avoid the problems of not being able to use the following characters in reference key names (source),
. (period)
$ (dollar sign)
[ (left square bracket)
] (right square bracket)
# (hash or pound sign)
/ (forward slash)
we can use one of JavaScript's built in encoding functions since as far as I can tell, Firebase does not provide a built in method to do so. Here's a run-through to see which is the most effective for our purposes:
var forbiddenChars = '.$[]#/'; //contains the forbidden characters
escape(forbiddenChars); //results in ".%24%5B%5D%23/"
encodeURI(forbiddenChars); //results in ".%24%5B%5D%23%2F"
encodeURIComponent(forbiddenChars); //results in ".%24%5B%5D%23%2F"
Evidently, the most effective solution is encodeURIComponent. However, it doesn't solve all our problems. The . character still poses a problem as shown by the above test and trying to encodeURIComponent your test e-mail address. My suggestion would be to chain a replace function after the encodeURIComponent to deal with the periods.
Here's what the solution would look like for your two example cases:
encodeURIComponent('Henry.Morgan#caribbean.sea').replace(/\./g, '%2E') //results in "Henry%2EMorgan%40caribbean%2Esea"
encodeURIComponent('02/10/2013'); //results in "02%2F10%2F2013"
Since both the final results are safe for insertion into a Firebase as a key name, the only other concern is decoding after reading from a Firebase which can be solved with replace('%2E', '.') and a simple decodeURIComponent(...).
I faced the same problem myself, and I have created firebase-encode for this purpose.
Unlike the chosen answer, firebase-encode encodes only unsafe characters (./[]#$) and % (necessary due to how encoding/decoding works).
It leaves other special characters that are safe to be used as firebase key while encodeURIComponent will encode them.
Here's the source code for details:
// http://stackoverflow.com/a/6969486/692528
const escapeRegExp = (str) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
const chars = '.$[]#/%'.split('');
const charCodes = chars.map((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
const charToCode = {};
const codeToChar = {};
chars.forEach((c, i) => {
charToCode[c] = charCodes[i];
codeToChar[charCodes[i]] = c;
});
const charsRegex = new RegExp(`[${escapeRegExp(chars.join(''))}]`, 'g');
const charCodesRegex = new RegExp(charCodes.join('|'), 'g');
const encode = (str) => str.replace(charsRegex, (match) => charToCode[match]);
const decode = (str) => str.replace(charCodesRegex, (match) => codeToChar[match]);
I wrote this for Java (since I came here expecting a java implementation):
public static String encodeForFirebaseKey(String s) {
return s
.replace("_", "__")
.replace(".", "_P")
.replace("$", "_D")
.replace("#", "_H")
.replace("[", "_O")
.replace("]", "_C")
.replace("/", "_S")
;
}
public static String decodeFromFirebaseKey(String s) {
int i = 0;
int ni;
String res = "";
while ((ni = s.indexOf("_", i)) != -1) {
res += s.substring(i, ni);
if (ni + 1 < s.length()) {
char nc = s.charAt(ni + 1);
if (nc == '_') {
res += '_';
} else if (nc == 'P') {
res += '.';
} else if (nc == 'D') {
res += '$';
} else if (nc == 'H') {
res += '#';
} else if (nc == 'O') {
res += '[';
} else if (nc == 'C') {
res += ']';
} else if (nc == 'S') {
res += '/';
} else {
// this case is due to bad encoding
}
i = ni + 2;
} else {
// this case is due to bad encoding
break;
}
}
res += s.substring(i);
return res;
}
Character limitations are documented at https://www.firebase.com/docs/creating-references.html - you cannot use '.', '/', '[', ']', '#', and '$' in key names. There is no automatic way of escaping these characters, I'd recommend avoiding their use altogether or creating your own escaping/unescaping mechanism.
If you're using Swift 3, this works for me (try it in a playground):
var str = "this.is/a#crazy[string]right$here.$[]#/"
if let strEncoded = str.addingPercentEncoding(withAllowedCharacters: .alphanumerics) {
print(strEncoded)
if let strDecoded = strEncoded.removingPercentEncoding {
print(strDecoded)
}
}
I got annoyed with this problem so I took the answer from #sushain97 (thanks!) and built a deep encoder/decoder.
https://www.npmjs.com/package/firebase-key-encode
Basic usage:
var firebaseKeyEncode = require('firebase-key-encode');
firebaseKeyEncode.encode('my.bad.key');
// Output: my%2Ebad%2Ekey
Deep Usage:
var firebaseKeyEncode = require('firebase-key-encode');
var badTree = {
"pets": [
{
"jimmy.choo": 15}
],
"other.key": 5
}
firebaseKeyEncode.deepEncode(badTree);
// Output: {
// "pets": [
// {
// "jimmy%2Echoo": 15}
// ],
// "other%2Ekey": 5
// }
Personally, I found a simple and easy hack for this same problem I encountered
I took the dateTime string and convert it using replace('/','|')
the result will be something like this 2017|07|24 02:39:37 instead of 2017/07/24 02:39:37.
Even though it is not what OP asks,
but in my experience rather than using such dubious keys it is better to let .push() create an id,
and other things - e-mail, date etc. save as content of the dedicated fields.
$id: {
email: "Henry.Morgan#caribbean.sea"
}
P.S. Don't try to save volume by inserting what should be content into the key.
Premature optimization is the root of all evil (c).
Efficient C# implementation (for Unity and .net). Based on the answer from #josue.0.
public static string EncodeFirebaseKey(string s) {
StringBuilder sb = new StringBuilder();
foreach (char c in s) {
switch (c) {
case '_':
sb.Append("__");
break;
case '$':
sb.Append("_D");
break;
case '.':
sb.Append("_P");
break;
case '#':
sb.Append("_H");
break;
case '[':
sb.Append("_O");
break;
case ']':
sb.Append("_C");
break;
case '/':
sb.Append("_S");
break;
default:
sb.Append(c);
break;
}
}
return sb.ToString();
}
public static string DecodeFirebaseKey(string s) {
StringBuilder sb = new StringBuilder();
bool underscore = false;
for (int i = 0; i < s.Length; i++) {
if (underscore) {
switch (s[i]) {
case '_':
sb.Append('_');
break;
case 'D':
sb.Append('$');
break;
case 'P':
sb.Append('.');
break;
case 'H':
sb.Append('#');
break;
case 'O':
sb.Append('[');
break;
case 'C':
sb.Append(']');
break;
case 'S':
sb.Append('/');
break;
default:
Debug.LogWarning("Bad firebase key for decoding");
break;
}
underscore = false;
} else {
switch (s[i]) {
case '_':
underscore = true;
break;
default:
sb.Append(s[i]);
break;
}
}
}
return sb.ToString();
}
Python implementation
_escape = {'&': '&&',
'$': '&36',
'#': '&35',
'[': '&91',
']': '&93',
'/': '&47',
'.': '&46'}
_unescape = {e: u for u, e in _escape.items()}
def escape_firebase_key(text):
return text.translate(str.maketrans(_escape))
def unescape_firebase_key(text):
chunks = []
i = 0
while True:
a = text[i:].find('&')
if a == -1:
return ''.join(chunks + [text[i:]])
else:
if text[i+a:i+a+2] == '&&':
chunks.append('&')
i += a+2
else:
s = text[i+a:i+a+3]
if s in _unescape:
chunks.append(text[i:i+a])
chunks.append(_unescape[s])
i += a+3
else:
raise RuntimeError('Cannot unescape')
And a few test cases:
test_pairs = [('&hello.', '&&hello&46'),
('&&&', '&&&&&&'),
('some#email.com', 'some#email&46com'),
('#$[]/.', '&35&36&91&93&47&46')]
for u, e in test_pairs:
assert escape_firebase_key(u) == e, f"escaped '{u}' is '{e}', but was '{escape_firebase_key(u)}'"""
assert unescape_firebase_key(e) == u, f"unescaped '{e}' is '{u}', but was '{unescape_firebase_key(e)}'"
try:
unescape_firebase_key('&error')
assert False, 'Must have raised an exception here'
except RuntimeError as ex:
assert str(ex) == 'Cannot unescape'
const encodeKey = s => s.replace(/[\.\$\[\]#\/%]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase())
const decodeKey = s => s.replace(/%(2E|24|5B|5D|23|2F|25)/g, decodeURIComponent)
console.log(encodeKey('.$[]#/%23')) // %2E%24%5B%5D%23%2F%2523
console.log(decodeKey(encodeKey('.$[]#/%23'))) // .$[]#/%23
import re
import urllib.parse
encode_key = lambda s: re.sub('[\.\$\[\]#\/%]', lambda c: f'%{ord(c.group()):X}', s)
decode_key = lambda s: re.sub('%(2E|24|5B|5D|23|2F|25)', lambda c: urllib.parse.unquote(c.group()), s)
print(encode_key('.$[]#/%23')) # %2E%24%5B%5D%23%2F%2523
print(decode_key(encode_key('.$[]#/%23'))) # .$[]#/%23

Check if multiline textbox has only newline characters

Using .Net 2.0 how can i check if a multi line text box has only newline characters?
No text at all, but only \n, \r, etc..?
if (Regex.IsMatch(#"^[\r\n]+$", text))
You can use String.IsNullOrWhiteSpace method.
if(!string.IsNullOrWhiteSpace(TextBox1.Text))
{
}
Here is the source of IsNullOrWhiteSpace -
public static bool IsNullOrWhiteSpace(string value)
{
if (value == null)
return true;
for (int index = 0; index < value.Length; ++index)
{
if (!char.IsWhiteSpace(value[index]))
return false;
}
return true;
}
Have you tried replacing Environment.NewLine with nothing?
For example,
Dim tbLen as Integer = tb.Text.Length() 'returns 2 for 1 return character
Dim tbLenFiltered As Integer = tb.Text.Replace(Environment.NewLine, String.Empty).Length() 'returns 0 for 1 return character

Convert a string to Decimal(10,2)

how can i convert a string to a Decimal(10,2) in C#?
Take a look at Decimal.TryParse, especially if the string is coming from a user.
You'll want to use TryParse if there's any chance the string cannot be converted to a Decimal. TryParse allows you to test if the conversion will work without throwing an Exception.
You got to be careful with that, because some cultures uses dots as a thousands separator and comma as a decimal separator.
My proposition for a secure string to decimal converstion:
public static decimal parseDecimal(string value)
{
value = value.Replace(" ", "");
if (System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == ",")
{
value = value.Replace(".", ",");
}
else
{
value = value.Replace(",", ".");
}
string[] splited = value.Split(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
if (splited.Length > 2)
{
string r = "";
for (int i = 0; i < splited.Length; i++)
{
if (i == splited.Length - 1)
r += System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
r += splited[i];
}
value = r;
}
return decimal.Parse(value);
}
The loop is in case that string contains both, decimal and thousand separator
Try:
string test = "123";
decimal test2 = Convert.ToDecimal(test);
//decimal test2 = Decimal.Parse(test);
//decimal test2;
// if (decimal.TryParse(test, out result))
//{ //valid }
//else
//{ //Exception }
labelConverted.Text = test2.toString();
Decimal Examples
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
Regards

How to match text in string in Arduino

I have some issues with Arduino about how to match text.
I have:
String tmp = +CLIP: "+37011111111",145,"",,"",0
And I am trying to match:
if (tmp.startsWith("+CLIP:")) {
mySerial.println("ATH0");
}
But this is not working, and I have no idea why.
I tried substring, but the result is the same. I don't know how to use it or nothing happens.
Where is the error?
bool Contains(String s, String search) {
int max = s.length() - search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i) == search) return true; // or i
}
return false; //or -1
}
Otherwise you could simply do:
if (readString.indexOf("+CLIP:") >=0)
I'd also recommend visiting:
https://www.arduino.cc/en/Reference/String
I modified the code from gotnull. Thanks to him to put me on the track.
I just limited the search string, otherwise the substring function was not returning always the correct answer (when substrign was not ending the string). Because substring search always to the end of the string.
int StringContains(String s, String search) {
int max = s.length() - search.length();
int lgsearch = search.length();
for (int i = 0; i <= max; i++) {
if (s.substring(i, i + lgsearch) == search) return i;
}
return -1;
}
//+CLIP: "43660417XXXX",145,"",0,"",0
if (strstr(command.c_str(), "+CLIP:")) { //Someone is calling
GSM.print(F("ATA\n\r"));
Number = command.substring(command.indexOf('"') + 1);
Number = Number.substring(0, Number.indexOf('"'));
//Serial.println(Number);
} //End of if +CLIP:
This is how I'm doing it. Hope it helps.
if (tmp.startsWith(String("+CLIP:"))) {
mySerial.println("ATH0");
}
You can't put the string with quotes only you need to cast the variable :)

Membership Generate Password alphanumeric only password?

How can I use Membership.GeneratePassword to return a password that ONLY contains alpha or numeric characters? The default method will only guarantee a minimum and not a maximum number of non alphanumeric passwords.
string newPassword = Membership.GeneratePassword(15, 0);
newPassword = Regex.Replace(newPassword, #"[^a-zA-Z0-9]", m => "9" );
This regular expression will replace all non alphanumeric characters with the numeric character 9.
I realised that there may be ways of doing this. The GUID method is great, except it doesn't mix UPPER and lower case alphabets. In my case it produced lower-case only.
So I decided to use the Regex to remove the non-alphas then substring the results to the length that I needed.
string newPassword = Membership.GeneratePassword(50, 0);
newPassword = Regex.Replace(newPassword, #"[^a-zA-Z0-9]", m => "");
newPassword = newPassword.Substring(0, 10);
A simple way to get an 8 character alphanumeric password would be to generate a guid and use that as the basis:
string newPwd = Guid.NewGuid().ToString().Substring(0, 8);
If you need a longer password, just skip over the dash using substrings:
string newPwd = Guid.NewGuid().ToString().Substring(0, 11);
newPwd = newPwd.Substring(0, 8) + newPwd.Substring(9, 2); // to skip the dash.
If you want to make sure the first character is alpha, you could just replace it when needed with a fixed string if (newPwd[0] >= '0' && newPwd[0] <= '9')...
I hope someone can find this helpful. :-)
You could also try to generate passwords and concatenate the non alphanumeric characters until you reach the desired password length.
public string GeneratePassword(int length)
{
var sb = new StringBuilder(length);
while (sb.Length < length)
{
var tmp = System.Web.Security.Membership.GeneratePassword(length, 0);
foreach(var c in tmp)
{
if(char.IsLetterOrDigit(c))
{
sb.Append(c);
if (sb.Length == length)
{
break;
}
}
}
}
return sb.ToString();
}
There is similar approach with breigo's solution.
Maybe this is not so effective but so clear and short
string GeneratePassword(int length)
{
var password = "";
while (password.Length < length)
{
password += string.Concat(Membership.GeneratePassword(1, 0).Where(char.IsLetterOrDigit));
}
return password;
}
I also prefer the GUID method - here's the short version:
string password = Guid.NewGuid().ToString("N").Substring(0, 8);
Going from #SollyM's answer, putting a while loop around it, to prevent the very unlikely event of all characters, or too many characters being special characters, and then substring throwing an exception.
private string GetAlphaNumericRandomString(int length)
{
string randomString = "";
while (randomString.Length < length)
{
//generates a random string, of twice the length specified, to counter the
//probability of the while loop having to run a second time
randomString += Membership.GeneratePassword(length * 2, 0);
//replace non alphanumeric characters
randomString = Regex.Replace(randomString, #"[^a-zA-Z0-9]", m => "");
}
return randomString.Substring(0, length);
}
This is what I use:
public class RandomGenerator
{
//Guid.NewGuid().ToString().Replace("-", "");
//System.Web.Security.Membership.GeneratePassword(12, 0);
private static string AllowChars_Numeric = "0123456789";
private static string AllowChars_EasyUpper = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static string AllowChars_EasyLower = "0123456789abcdefghijklmnopqrstuvwxyz";
private static string AllowChars_Upper_Lower = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static string AllowedChars_Difficult = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz##$^*()";
public enum Difficulty
{
NUMERIC = 1,
EASY_LOWER = 2,
EASY_UPPER = 3,
UPPER_LOWER = 4,
DIFFICULT = 5
}
public static string GetRandomString(int length, Difficulty difficulty)
{
Random rng = new Random();
string charBox = AllowedChars_Difficult;
switch (difficulty)
{
case Difficulty.NUMERIC:
charBox = AllowChars_Numeric;
break;
case Difficulty.EASY_LOWER:
charBox = AllowChars_EasyUpper;
break;
case Difficulty.EASY_UPPER:
charBox = AllowChars_EasyLower;
break;
case Difficulty.UPPER_LOWER:
charBox = AllowChars_Upper_Lower;
break;
case Difficulty.DIFFICULT:
default:
charBox = AllowedChars_Difficult;
break;
}
char[] chars = new char[length];
for (int i=0; i< length; i++)
{
chars[i] = charBox[rng.Next(0, charBox.Length)];
}
return new string(chars);
}
}

Resources