How to check if string contains both uppercase and lowercase characters - string

I need to validate password entered by user and check if the password contains at least one uppercase and one lowercase char in Dart.
I wrote this String extension:
extension StringValidators on String {
bool containsUppercase() {
// What code should be here?
}
bool containsLowercase() {
// What code should be here?
}
}
And use it like this:
final text = passwordTextController.text;
final isValid = text.containsUppercase() && text.containsLowercase();
Is there any regexp for this purpose? Or it should be plain algorithm? Please help me to find out the elegant way. Thanks!

Minimum 1 Upper case,
Minimum 1 lowercase,
Minimum 1 Numeric Number,
Minimum 1 Special Character,
Common Allow Character ( ! # # $ & * ~ )
bool validateStructure(String value){
String pattern = r'^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[!##\$&*~]).{8,}$';
RegExp regExp = new RegExp(pattern);
return regExp.hasMatch(value);
}

extension StringValidators on String {
bool get containsUppercase => contains(RegExp(r'[A-Z]'));
bool get containsLowercase => contains(RegExp(r'[a-z]'));
}

For only minimum 1 upper and minimum 1 Lower only, you could use this RegEx:
RegExp regEx = new RegExp(r"(?=.*[a-z])(?=.*[A-Z])\w+");
String a = "aBc";
String b = "abc";
String c = "ABC";
print("a => " + regEx.hasMatch(a).toString());
print("b => " + regEx.hasMatch(b).toString());
print("c => " + regEx.hasMatch(c).toString());
Expected Result:
I/flutter (10220): a => true
I/flutter (10220): b => false
I/flutter (10220): c => false
Reusable
extension StringValidators on String {
meetsPasswordRequirements() {
RegExp regEx = new RegExp(r"(?=.*[a-z])(?=.*[A-Z])\w+");
return regEx.hasMatch(this);
}
}
Use
final isValid = text.meetsPasswordRequirements();

void main() {
solve("coDE");
}
String solve(String s) {
// your code here
List _a = s.split("");
String _b = "";
List _x = [];
List _y = [];
for(var i in _a){
if(i.toString() == i.toString().toUpperCase()){
_x.add(i);
}else{
_y.add(i);
}
}
if(_x.length == _y.length){
_b = _a.join().toLowerCase();
}else if(_x.length > _y.length){
_b = _a.join().toUpperCase();
}else if(_x.length < _y.length){
_b = _a.join().toLowerCase();
}
return "$_b";
}
OR
String solve2(String str) {
return RegExp(r'[A-Z]').allMatches(str).length >
RegExp(r'[a-z]').allMatches(str).length
? str.toUpperCase()
: str.toLowerCase();
}

Related

How do I check to see if a character is a space character in Swift?

In a program I'm writing, I need to check to see if a character is a space (" "). Currently have this as the conditional but it's not working. Any ideas? Thanks in advance.
for(var k = indexOfCharBeingExamined; k < lineBeingExaminedChars.count; k++){
let charBeingExamined = lineBeingExaminedChars[lineBeingExaminedChars.startIndex.advancedBy(k)];
//operations
if(String(charBeingExamined) == " "){
//more operations
}
}
The code below is how I solved this problem with a functional approach in Swift. I made an extension (two, actually), but you could easily take the guts of the function and use it elsewhere.
extension String {
var isWhitespace: Bool {
guard !isEmpty else { return true }
let whitespaceChars = NSCharacterSet.whitespacesAndNewlines
return self.unicodeScalars
.filter { !whitespaceChars.contains($0) }
.count == 0
}
}
extension Optional where Wrapped == String {
var isNullOrWhitespace: Bool {
return self?.isWhitespace ?? true
}
}
The following code works for me. Note that it's easier to just iterate over the characters in a string using 'for' (second example below):
var s = "X yz"
for var i = 0; i < s.characters.count; i++ {
let x = s[s.startIndex.advancedBy(i)]
print(x)
print(String(x) == " ")
}
for c in s.characters {
print(c)
print(String(c) == " ")
}
String:
let origin = "Some string with\u{00a0}whitespaces" // \u{00a0} is a no-break space
Oneliner:
let result = origin.characters.contains { " \u{00a0}".characters.contains($0) }
Another approach:
let spaces = NSCharacterSet.whitespaceCharacterSet()
let result = origin.utf16.contains { spaces.characterIsMember($0) }
Output:
print(result) // true
Not sure what you want to do with the spaces, because then it could be a bit simpler.
just in your code change " " -> "\u{00A0}"
for(var k = indexOfCharBeingExamined; k < lineBeingExaminedChars.count; k++){
let charBeingExamined = lineBeingExaminedChars[lineBeingExaminedChars.startIndex.advancedBy(k)];
if(String(charBeingExamined) == "\u{00A0}"){
//more operations
}
}
To test just for whitespace:
func hasWhitespace(_ input: String) -> Bool {
let inputCharacterSet = CharacterSet(charactersIn: input)
return !inputCharacterSet.intersection(CharacterSet.whitespaces).isEmpty
}
To test for both whitespace and an empty string:
func hasWhitespace(_ input: String) -> Bool {
let inputCharacterSet = CharacterSet(charactersIn: input)
return !inputCharacterSet.intersection(CharacterSet.whitespaces).isEmpty || inputCharacterSet.isEmpty
}

Swift 2 : Iterating and upper/lower case some characters

I want to modify a Swift string by converting some characters to uppercase, some others to lowercase.
In Obj-c I had following :
- (NSString*) lowercaseDestination:(NSString*) string {
NSUInteger length = string.length;
unichar buf[length+1];
[string getCharacters:buf];
BOOL up = true;
for (int i=0; i< length ; i++) {
unichar chr = buf[i];
if( .... ) {
buf[i] = toupper(chr);
} else {
buf[i] = tolower(chr);
}
}
string = [NSString stringWithCharacters:buf length:length];
return string;
How would you do that in Swift 2 ?
I did no find any Character method to upper or lower the case.
Would be an array of String of 1 character be an option ? (And then use String methods to upper and lower each String
String has a upperCaseString method, but Character doesn't.
The reason is that in exotic languages like German, converting a single
character to upper case can result in multiple characters:
print("ß".uppercaseString) // "SS"
The toupper/tolower functions are not Unicode-safe and not
available in Swift.
So you can enumerate the string characters, convert each character to
a string, convert that to upper/lowercase, and concatenate the results:
func lowercaseDestination(str : String) -> String {
var result = ""
for c in str.characters {
let s = String(c)
if condition {
result += s.lowercaseString
} else {
result += s.uppercaseString
}
}
return result
}
which can be written more compactly as
func lowercaseDestination(str : String) -> String {
return "".join(str.characters.map { c -> String in
let s = String(c)
return condition ? s.lowercaseString : s.uppercaseString
})
}
Re your comment: If the condition needs to check more than one
character then you might want to create an array of all characters
first:
func lowercaseDestination(str : String) -> String {
var result = ""
let characters = Array(str.characters)
for i in 0 ..< characters.count {
let s = String(characters[i])
if condition {
result += s.lowercaseString
} else {
result += s.uppercaseString
}
}
return result
}

Checking if string is numeric in dart

I need to find out if a string is numeric in dart. It needs to return true on any valid number type in dart. So far, my solution is
bool isNumeric(String str) {
try{
var value = double.parse(str);
} on FormatException {
return false;
} finally {
return true;
}
}
Is there a native way to do this? If not, is there a better way to do it?
This can be simpliefied a bit
void main(args) {
print(isNumeric(null));
print(isNumeric(''));
print(isNumeric('x'));
print(isNumeric('123x'));
print(isNumeric('123'));
print(isNumeric('+123'));
print(isNumeric('123.456'));
print(isNumeric('1,234.567'));
print(isNumeric('1.234,567'));
print(isNumeric('-123'));
print(isNumeric('INFINITY'));
print(isNumeric(double.INFINITY.toString())); // 'Infinity'
print(isNumeric(double.NAN.toString()));
print(isNumeric('0x123'));
}
bool isNumeric(String s) {
if(s == null) {
return false;
}
return double.parse(s, (e) => null) != null;
}
false // null
false // ''
false // 'x'
false // '123x'
true // '123'
true // '+123'
true // '123.456'
false // '1,234.567'
false // '1.234,567' (would be a valid number in Austria/Germany/...)
true // '-123'
false // 'INFINITY'
true // double.INFINITY.toString()
true // double.NAN.toString()
false // '0x123'
from double.parse DartDoc
* Examples of accepted strings:
*
* "3.14"
* " 3.14 \xA0"
* "0."
* ".0"
* "-1.e3"
* "1234E+7"
* "+.12e-9"
* "-NaN"
This version accepts also hexadecimal numbers
bool isNumeric(String s) {
if(s == null) {
return false;
}
// TODO according to DartDoc num.parse() includes both (double.parse and int.parse)
return double.parse(s, (e) => null) != null ||
int.parse(s, onError: (e) => null) != null;
}
print(int.parse('0xab'));
true
UPDATE
Since {onError(String source)} is deprecated now you can just use tryParse:
bool isNumeric(String s) {
if (s == null) {
return false;
}
return double.tryParse(s) != null;
}
In Dart 2 this method is deprecated
int.parse(s, onError: (e) => null)
instead, use
bool _isNumeric(String str) {
if(str == null) {
return false;
}
return double.tryParse(str) != null;
}
Even shorter. Despite the fact it will works with double as well, using num is more accurately.
isNumeric(string) => num.tryParse(string) != null;
num.tryParse inside:
static num tryParse(String input) {
String source = input.trim();
return int.tryParse(source) ?? double.tryParse(source);
}
for anyone wanting a non native way using regex
RegExp _numeric = RegExp(r'^-?[0-9]+$');
/// check if the string contains only numbers
bool isNumeric(String str) {
return _numeric.hasMatch(str);
}
if (int.tryParse(value) == null) {
return 'Only Number are allowed';
}
Yes, there is a more "sophisticated" way *rsrs*.
extension Numeric on String {
bool get isNumeric => num.tryParse(this) != null ? true : false;
}
main() {
print("1".isNumeric); // true
print("-1".isNumeric); // true
print("2.5".isNumeric); // true
print("-2.5".isNumeric); // true
print("0x14f".isNumeric); // true
print("2,5".isNumeric); // false
print("2a".isNumeric); // false
}
import 'dart:convert';
void main() {
//------------------------allMatches Example---------------------------------
print('Example 1');
//We want to extract ages from the following string:
String str1 = 'Sara is 26 years old. Maria is 18 while Masood is 8.';
//Declaring a RegExp object with a pattern that matches sequences of digits
RegExp reg1 = new RegExp(r'(\d+)');
//Iterating over the matches returned from allMatches
Iterable allMatches = reg1.allMatches(str1);
var matchCount = 0;
allMatches.forEach((match) {
matchCount += 1;
print('Match ${matchCount}: ' + str1.substring(match.start, match.end));
});
//------------------------firstMatch Example---------------------------------
print('\nExample 2');
//We want to find the first sequence of word characters in the following string:
//Note: A word character is any single letter, number or underscore
String str2 = '#%^!_as22 d3*fg%';
//Declaring a RegExp object with a pattern that matches sequences of word
//characters
RegExp reg2 = new RegExp(r'(\w+)');
//Using the firstMatch function to display the first match found
Match firstMatch = reg2.firstMatch(str2) as Match;
print('First match: ${str2.substring(firstMatch.start, firstMatch.end)}');
//--------------------------hasMatch Example---------------------------------
print('\nExample 3');
//We want to check whether a following strings have white space or not
String str3 = 'Achoo!';
String str4 = 'Bless you.';
//Declaring a RegExp object with a pattern that matches whitespaces
RegExp reg3 = new RegExp(r'(\s)');
//Using the hasMatch method to check strings for whitespaces
print(
'The string "' + str3 + '" contains whitespaces: ${reg3.hasMatch(str3)}');
print(
'The string "' + str4 + '" contains whitespaces: ${reg3.hasMatch(str4)}');
//--------------------------stringMatch Example-------------------------------
print('\nExample 4');
//We want to print the first non-digit sequence in the following strings;
String str5 = '121413dog299toy01food';
String str6 = '00Tom1231frog';
//Declaring a RegExp object with a pattern that matches sequence of non-digit
//characters
RegExp reg4 = new RegExp(r'(\D+)');
//Using the stringMatch method to find the first non-digit match:
String? str5Match = reg4.stringMatch(str5);
String? str6Match = reg4.stringMatch(str6);
print('First match for "' + str5 + '": $str5Match');
print('First match for "' + str6 + '": $str6Match');
//--------------------------matchAsPrefix Example-----------------------------
print('\nExample 5');
//We want to check if the following strings start with the word "Hello" or not:
String str7 = 'Greetings, fellow human!';
String str8 = 'Hello! How are you today?';
//Declaring a RegExp object with a pattern that matches the word "Hello"
RegExp reg5 = new RegExp(r'Hello');
//Using the matchAsPrefix method to match "Hello" to the start of the strings
Match? str7Match = reg5.matchAsPrefix(str7);
Match? str8Match = reg5.matchAsPrefix(str8);
print('"' + str7 + '" starts with hello: ${str7Match != null}');
print('"' + str8 + '" starts with hello: ${str8Match != null}');
}
bool isOnlyNumber(String str) {
try{
var value = int.parse(str);
return true;
} on FormatException {
return false;
}
}
Building on Matso Abgaryan's answer and GΓΌnter ZΓΆchbauer's updated answer,
I can get a ',' (comma) on my numeric soft keyboard while developing mobile apps in flutter, and double.tryParse() can return Nan as well as null - so checking vs null is not enough if a user can enter a comma on a soft numeric keyboard. If a string is empty, using double.tryParse() will produce null - so that edge case will be caught using this function;
bool _isNumeric(String str) {
if (str == null) {
return false;
}
return double.tryParse(str) is double;
}
Documentation for tryParse()

Finding index of character in Swift String

It's time to admit defeat...
In Objective-C, I could use something like:
NSString* str = #"abcdefghi";
[str rangeOfString:#"c"].location; // 2
In Swift, I see something similar:
var str = "abcdefghi"
str.rangeOfString("c").startIndex
...but that just gives me a String.Index, which I can use to subscript back into the original string, but not extract a location from.
FWIW, that String.Index has a private ivar called _position that has the correct value in it. I just don't see how it's exposed.
I know I could easily add this to String myself. I'm more curious about what I'm missing in this new API.
You are not the only one who couldn't find the solution.
String doesn't implement RandomAccessIndexType. Probably because they enable characters with different byte lengths. That's why we have to use string.characters.count (count or countElements in Swift 1.x) to get the number of characters. That also applies to positions. The _position is probably an index into the raw array of bytes and they don't want to expose that. The String.Index is meant to protect us from accessing bytes in the middle of characters.
That means that any index you get must be created from String.startIndex or String.endIndex (String.Index implements BidirectionalIndexType). Any other indices can be created using successor or predecessor methods.
Now to help us with indices, there is a set of methods (functions in Swift 1.x):
Swift 4.x
let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.index(text.startIndex, offsetBy: 2)
let lastChar2 = text[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
Swift 3.0
let text = "abc"
let index2 = text.index(text.startIndex, offsetBy: 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let characterIndex2 = text.characters.index(text.characters.startIndex, offsetBy: 2)
let lastChar2 = text.characters[characterIndex2] //will do the same as above
let range: Range<String.Index> = text.range(of: "b")!
let index: Int = text.distance(from: text.startIndex, to: range.lowerBound)
Swift 2.x
let text = "abc"
let index2 = text.startIndex.advancedBy(2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let lastChar2 = text.characters[index2] //will do the same as above
let range: Range<String.Index> = text.rangeOfString("b")!
let index: Int = text.startIndex.distanceTo(range.startIndex) //will call successor/predecessor several times until the indices match
Swift 1.x
let text = "abc"
let index2 = advance(text.startIndex, 2) //will call succ 2 times
let lastChar: Character = text[index2] //now we can index!
let range = text.rangeOfString("b")
let index: Int = distance(text.startIndex, range.startIndex) //will call succ/pred several times
Working with String.Index is cumbersome but using a wrapper to index by integers (see https://stackoverflow.com/a/25152652/669586) is dangerous because it hides the inefficiency of real indexing.
Note that Swift indexing implementation has the problem that indices/ranges created for one string cannot be reliably used for a different string, for example:
Swift 2.x
let text: String = "abc"
let text2: String = "πŸŽΎπŸ‡πŸˆ"
let range = text.rangeOfString("b")!
//can randomly return a bad substring or throw an exception
let substring: String = text2[range]
//the correct solution
let intIndex: Int = text.startIndex.distanceTo(range.startIndex)
let startIndex2 = text2.startIndex.advancedBy(intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]
Swift 1.x
let text: String = "abc"
let text2: String = "πŸŽΎπŸ‡πŸˆ"
let range = text.rangeOfString("b")
//can randomly return nil or a bad substring
let substring: String = text2[range]
//the correct solution
let intIndex: Int = distance(text.startIndex, range.startIndex)
let startIndex2 = advance(text2.startIndex, intIndex)
let range2 = startIndex2...startIndex2
let substring: String = text2[range2]
Swift 3.0 makes this a bit more verbose:
let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.index(of: needle) {
let pos = string.characters.distance(from: string.startIndex, to: idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
Extension:
extension String {
public func index(of char: Character) -> Int? {
if let idx = characters.index(of: char) {
return characters.distance(from: startIndex, to: idx)
}
return nil
}
}
In Swift 2.0 this has become easier:
let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.indexOf(needle) {
let pos = string.startIndex.distanceTo(idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
Extension:
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let idx = self.characters.indexOf(char) {
return self.startIndex.distanceTo(idx)
}
return nil
}
}
Swift 1.x implementation:
For a pure Swift solution one can use:
let string = "Hello.World"
let needle: Character = "."
if let idx = find(string, needle) {
let pos = distance(string.startIndex, idx)
println("Found \(needle) at position \(pos)")
}
else {
println("Not found")
}
As an extension to String:
extension String {
public func indexOfCharacter(char: Character) -> Int? {
if let idx = find(self, char) {
return distance(self.startIndex, idx)
}
return nil
}
}
Swift 5.0
public extension String {
func indexInt(of char: Character) -> Int? {
return firstIndex(of: char)?.utf16Offset(in: self)
}
}
Swift 4.0
public extension String {
func indexInt(of char: Character) -> Int? {
return index(of: char)?.encodedOffset
}
}
extension String {
// MARK: - sub String
func substringToIndex(index:Int) -> String {
return self.substringToIndex(advance(self.startIndex, index))
}
func substringFromIndex(index:Int) -> String {
return self.substringFromIndex(advance(self.startIndex, index))
}
func substringWithRange(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self.substringWithRange(start..<end)
}
subscript(index:Int) -> Character{
return self[advance(self.startIndex, index)]
}
subscript(range:Range<Int>) -> String {
let start = advance(self.startIndex, range.startIndex)
let end = advance(self.startIndex, range.endIndex)
return self[start..<end]
}
// MARK: - replace
func replaceCharactersInRange(range:Range<Int>, withString: String!) -> String {
var result:NSMutableString = NSMutableString(string: self)
result.replaceCharactersInRange(NSRange(range), withString: withString)
return result
}
}
I have found this solution for swift2:
var str = "abcdefghi"
let indexForCharacterInString = str.characters.indexOf("c") //returns 2
I'm not sure how to extract the position from String.Index, but if you're willing to fall back on some Objective-C frameworks, you can bridge to objective-c and do it the same way you used to.
"abcdefghi".bridgeToObjectiveC().rangeOfString("c").location
It seems like some NSString methods haven't yet been (or maybe won't be) ported to String. Contains also comes to mind.
Here is a clean String extention that answers the question:
Swift 3:
extension String {
var length:Int {
return self.characters.count
}
func indexOf(target: String) -> Int? {
let range = (self as NSString).range(of: target)
guard range.toRange() != nil else {
return nil
}
return range.location
}
func lastIndexOf(target: String) -> Int? {
let range = (self as NSString).range(of: target, options: NSString.CompareOptions.backwards)
guard range.toRange() != nil else {
return nil
}
return self.length - range.location - 1
}
func contains(s: String) -> Bool {
return (self.range(of: s) != nil) ? true : false
}
}
Swift 2.2:
extension String {
var length:Int {
return self.characters.count
}
func indexOf(target: String) -> Int? {
let range = (self as NSString).rangeOfString(target)
guard range.toRange() != nil else {
return nil
}
return range.location
}
func lastIndexOf(target: String) -> Int? {
let range = (self as NSString).rangeOfString(target, options: NSStringCompareOptions.BackwardsSearch)
guard range.toRange() != nil else {
return nil
}
return self.length - range.location - 1
}
func contains(s: String) -> Bool {
return (self.rangeOfString(s) != nil) ? true : false
}
}
You can also find indexes of a character in a single string like this,
extension String {
func indexes(of character: String) -> [Int] {
precondition(character.count == 1, "Must be single character")
return self.enumerated().reduce([]) { partial, element in
if String(element.element) == character {
return partial + [element.offset]
}
return partial
}
}
}
Which gives the result in [String.Distance] ie. [Int], like
"apple".indexes(of: "p") // [1, 2]
"element".indexes(of: "e") // [0, 2, 4]
"swift".indexes(of: "j") // []
Swift 5
Find index of substring
let str = "abcdecd"
if let range: Range<String.Index> = str.range(of: "cd") {
let index: Int = str.distance(from: str.startIndex, to: range.lowerBound)
print("index: ", index) //index: 2
}
else {
print("substring not found")
}
Find index of Character
let str = "abcdecd"
if let firstIndex = str.firstIndex(of: "c") {
let index: Int = str.distance(from: str.startIndex, to: firstIndex)
print("index: ", index) //index: 2
}
else {
print("symbol not found")
}
If you want to use familiar NSString, you can declare it explicitly:
var someString: NSString = "abcdefghi"
var someRange: NSRange = someString.rangeOfString("c")
I'm not sure yet how to do this in Swift.
If you want to know the position of a character in a string as an int value use this:
let loc = newString.range(of: ".").location
This worked for me,
var loc = "abcdefghi".rangeOfString("c").location
NSLog("%d", loc);
this worked too,
var myRange: NSRange = "abcdefghi".rangeOfString("c")
var loc = myRange.location
NSLog("%d", loc);
I know this is old and an answer has been accepted, but you can find the index of the string in a couple lines of code using:
var str : String = "abcdefghi"
let characterToFind: Character = "c"
let characterIndex = find(str, characterToFind) //returns 2
Some other great information about Swift strings here Strings in Swift
Variable type String in Swift contains different functions compared to NSString in Objective-C . And as Sulthan mentioned,
Swift String doesn't implement RandomAccessIndex
What you can do is downcast your variable of type String to NSString (this is valid in Swift). This will give you access to the functions in NSString.
var str = "abcdefghi" as NSString
str.rangeOfString("c").locationx // returns 2
If you think about it, you actually don't really need the exact Int version of the location. The Range or even the String.Index is enough to get the substring out again if needed:
let myString = "hello"
let rangeOfE = myString.rangeOfString("e")
if let rangeOfE = rangeOfE {
myString.substringWithRange(rangeOfE) // e
myString[rangeOfE] // e
// if you do want to create your own range
// you can keep the index as a String.Index type
let index = rangeOfE.startIndex
myString.substringWithRange(Range<String.Index>(start: index, end: advance(index, 1))) // e
// if you really really need the
// Int version of the index:
let numericIndex = distance(index, advance(index, 1)) // 1 (type Int)
}
The Simplest Way is:
In Swift 3:
var textViewString:String = "HelloWorld2016"
guard let index = textViewString.characters.index(of: "W") else { return }
let mentionPosition = textViewString.distance(from: index, to: textViewString.endIndex)
print(mentionPosition)
String is a bridge type for NSString, so add
import Cocoa
to your swift file and use all the "old" methods.
In terms of thinking this might be called an INVERSION. You discover the world is round instead of flat. "You don't really need to know the INDEX of the character to do things with it." And as a C programmer I found that hard to take too!
Your line "let index = letters.characters.indexOf("c")!" is enough by itself.
For example to remove the c you could use...(playground paste in)
var letters = "abcdefg"
//let index = letters.rangeOfString("c")!.startIndex //is the same as
let index = letters.characters.indexOf("c")!
range = letters.characters.indexOf("c")!...letters.characters.indexOf("c")!
letters.removeRange(range)
letters
However, if you want an index you need to return an actual INDEX not an Int as an Int value would require additional steps for any practical use. These extensions return an index, a count of a specific character, and a range which this playground plug-in-able code will demonstrate.
extension String
{
public func firstIndexOfCharacter(aCharacter: Character) -> String.CharacterView.Index? {
for index in self.characters.indices {
if self[index] == aCharacter {
return index
}
}
return nil
}
public func returnCountOfThisCharacterInString(aCharacter: Character) -> Int? {
var count = 0
for letters in self.characters{
if aCharacter == letters{
count++
}
}
return count
}
public func rangeToCharacterFromStart(aCharacter: Character) -> Range<Index>? {
for index in self.characters.indices {
if self[index] == aCharacter {
let range = self.startIndex...index
return range
}
}
return nil
}
}
var MyLittleString = "MyVery:important String"
var theIndex = MyLittleString.firstIndexOfCharacter(":")
var countOfColons = MyLittleString.returnCountOfThisCharacterInString(":")
var theCharacterAtIndex:Character = MyLittleString[theIndex!]
var theRange = MyLittleString.rangeToCharacterFromStart(":")
MyLittleString.removeRange(theRange!)
Swift 4 Complete Solution:
OffsetIndexableCollection (String using Int Index)
https://github.com/frogcjn/OffsetIndexableCollection-String-Int-Indexable-
let a = "01234"
print(a[0]) // 0
print(a[0...4]) // 01234
print(a[...]) // 01234
print(a[..<2]) // 01
print(a[...2]) // 012
print(a[2...]) // 234
print(a[2...3]) // 23
print(a[2...2]) // 2
if let number = a.index(of: "1") {
print(number) // 1
print(a[number...]) // 1234
}
if let number = a.index(where: { $0 > "1" }) {
print(number) // 2
}
extension String {
//Fucntion to get the index of a particular string
func index(of target: String) -> Int? {
if let range = self.range(of: target) {
return characters.distance(from: startIndex, to: range.lowerBound)
} else {
return nil
}
}
//Fucntion to get the last index of occurence of a given string
func lastIndex(of target: String) -> Int? {
if let range = self.range(of: target, options: .backwards) {
return characters.distance(from: startIndex, to: range.lowerBound)
} else {
return nil
}
}
}
You can find the index number of a character in a string with this:
var str = "abcdefghi"
if let index = str.firstIndex(of: "c") {
let distance = str.distance(from: str.startIndex, to: index)
// distance is 2
}
If you are looking for easy way to get index of Character or String checkout this library http://www.dollarswift.org/#indexof-char-character-int
You can get the indexOf from a string using another string as well or regex pattern
To get index of a substring in a string with Swift 2:
let text = "abc"
if let range = text.rangeOfString("b") {
var index: Int = text.startIndex.distanceTo(range.startIndex)
...
}
In swift 2.0
var stringMe="Something In this.World"
var needle="."
if let idx = stringMe.characters.indexOf(needle) {
let pos=stringMe.substringFromIndex(idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
let mystring:String = "indeep";
let findCharacter:Character = "d";
if (mystring.characters.contains(findCharacter))
{
let position = mystring.characters.indexOf(findCharacter);
NSLog("Position of c is \(mystring.startIndex.distanceTo(position!))")
}
else
{
NSLog("Position of c is not found");
}
I play with following
extension String {
func allCharactes() -> [Character] {
var result: [Character] = []
for c in self.characters {
result.append(c)
}
return
}
}
until I understand the provided one's now it's just Character array
and with
let c = Array(str.characters)
If you only need the index of a character the most simple, quick solution (as already pointed out by Pascal) is:
let index = string.characters.index(of: ".")
let intIndex = string.distance(from: string.startIndex, to: index)
On the subject of turning a String.Index into an Int, this extension works for me:
public extension Int {
/// Creates an `Int` from a given index in a given string
///
/// - Parameters:
/// - index: The index to convert to an `Int`
/// - string: The string from which `index` came
init(_ index: String.Index, in string: String) {
self.init(string.distance(from: string.startIndex, to: index))
}
}
Example usage relevant to this question:
var testString = "abcdefg"
Int(testString.range(of: "c")!.lowerBound, in: testString) // 2
testString = "πŸ‡¨πŸ‡¦πŸ‡ΊπŸ‡ΈπŸ‡©πŸ‡ͺπŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦\u{1112}\u{1161}\u{11AB}"
Int(testString.range(of: "πŸ‡¨πŸ‡¦πŸ‡ΊπŸ‡ΈπŸ‡©πŸ‡ͺ")!.lowerBound, in: testString) // 0
Int(testString.range(of: "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦")!.lowerBound, in: testString) // 1
Int(testString.range(of: "ᄒᅑᆫ")!.lowerBound, in: testString) // 5
Important:
As you can tell, it groups extended grapheme clusters and joined characters differently than String.Index. Of course, this is why we have String.Index. You should keep in mind that this method considers clusters to be singular characters, which is closer to correct. If your goal is to split a string by Unicode codepoint, this is not the solution for you.
In Swift 2.0, the following function returns a substring before a given character.
func substring(before sub: String) -> String {
if let range = self.rangeOfString(sub),
let index: Int = self.startIndex.distanceTo(range.startIndex) {
return sub_range(0, index)
}
return ""
}
As my perspective, The better way with knowing the logic itself is below
let testStr: String = "I love my family if you Love us to tell us I'm with you"
var newStr = ""
let char:Character = "i"
for value in testStr {
if value == char {
newStr = newStr + String(value)
}
}
print(newStr.count)

How to move characters to certain points

I have a problem in which I have to SWAP or move characters and integers. Like I have any characters A . now I have some cases, like
NOTE:- Have to use characters A-Z and integers 0-9
A, now I want that when my program run I assign some integer value to this character, If I assign value 3 to this character then A will become D or it just move to 3 places.
Now if I have a character like Y and I add 4 then it will become C means after Z it will again start from character A.
Same condition I have to follow with Integer if i have 9 and we assign 3 to it then it will become 2 because loop start from 0 not from 1. Means we have to use only 0-9 integers.
I know that i am using wrong name to question but i have no idea that what lines i have to use for that kind of question.
Hope you understand my problem.
Thanks in advance.
Try the below extension method, which does the following:
It creates 2 dictionaries in order to speed up the key look up in the alphabet
Will parse the inputString variable, split it in substrings of the length of the moveString variable's length (or the remainder)
On every substring, it will evaluate each character in order to detect if it's a digit
If it's not a digit, it looks up for the value in the swappedAlphabet dictionary, by using the int key
If it's a digit, it applies a modulo operation on the sum of the digit and the corresponding moveint value
It finally aggregates all the characters in the final result string
Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string inputString = "ABC123D", moveString = "12";
var result = inputString.Swap(alphabet, moveString);
Console.WriteLine(result);
}
}
static class ExtensionMethods
{
public static Dictionary<TValue, TKey>
SwapKeysValues<TKey, TValue>(this Dictionary<TKey, TValue> input)
{
var result = new Dictionary<TValue, TKey>();
input.ToList().ForEach((keyValuePair) =>
{
result.Add(keyValuePair.Value, keyValuePair.Key);
});
return result;
}
public static string Swap(
this string input,
string alphabet,
string move)
{
Dictionary<char, int>
alphabetDictionary = new Dictionary<char, int>();
for (int i = 0; i < alphabet.Length; i++)
{
alphabetDictionary.Add(alphabet[i], i);
}
var swapedAlphabet = alphabetDictionary.SwapKeysValues();
return Enumerable
.Range(0, (int)Math.Ceiling(input.Length / (move.Length * 1M)))
.ToList()
.Aggregate<int, string>("", (s, i) =>
{
var l = i * move.Length + move.Length;
var cInput = input.Substring(i * move.Length,
(l > input.Length)
? input.Length - i * move.Length : move.Length);
return s + cInput
.Select((c, index) =>
{
int intCandidate;
if (!Int32.TryParse(c.ToString(), out intCandidate))
{
var length = (alphabetDictionary[c] +
Int32.Parse(move[index].ToString()));
return
swapedAlphabet[(alphabet.Length > length)
? length : length % alphabet.Length];
}
else
{
var moveInt = Int32.Parse(move[index].ToString());
return Char.Parse(((intCandidate + moveInt) % 10)
.ToString());
}
})
.Aggregate<char, string>("", (a, b) => a + b);
});
}
}
Another alternative you have is relying on the in-built character/integer types which follow the order you want; with an additional consideration: if you account for caps, it would deliver caps ("B" after "A" and "b" after "a"). The only thing you need to worry about is making sure that the iterations will be limited to the A-Z/0-9 boundaries. Sample code:
public string moveChar(string inputChar, int noPos)
{
string outChar = checkBoundaries(inputChar, noPos);
if (outChar == "")
{
outChar = basicConversion(inputChar, noPos);
}
return outChar;
}
public string basicConversion(string inputChar, int noPos)
{
return Convert.ToString(Convert.ToChar(Convert.ToInt32(Convert.ToChar(inputChar)) + noPos));
}
public string checkBoundaries(string inputChar, int noPos)
{
string outString = "";
int count1 = 0;
do
{
count1 = count1 + 1;
string curTemp = basicConversion(inputChar, 1);
if (inputChar.ToLower() == "z" || curTemp.ToLower() == "z")
{
if (inputChar.ToLower() != "z")
{
noPos = noPos - count1;
}
inputChar = "a";
outString = "a";
if (inputChar == "Z" || curTemp == "Z")
{
inputChar = "A";
outString = "A";
}
count1 = 1;
}
else if (inputChar == "9" || curTemp == "9")
{
if (inputChar != "9")
{
noPos = noPos - count1;
}
inputChar = "0";
outString = "0";
count1 = 1;
}
else
{
inputChar = curTemp;
outString = inputChar;
}
} while (count1 < noPos);
return outString;
}
It expects strings (just one character (letter or number) per call) and you can call it simply by using: moveChar("current letter or number", no_of_pos_to_move). This version accounts just for "positive"/"forwards" movements but it might easily be edited to account for the inverse situation.
Here's a very simple way to implement a Caesar Cipher with the restrictions you defined.
var shift = 3;
var input = "HELLO WORLD 678";
var classAlphabets = new Dictionary<UnicodeCategory, string>
{
{ UnicodeCategory.SpaceSeparator, " " },
{ UnicodeCategory.UppercaseLetter, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" },
{ UnicodeCategory.DecimalDigitNumber, "0123456789" }
};
var encoded = input.ToUpperInvariant()
.Select(c => new { Alphabet = classAlphabets[Char.GetUnicodeCategory(c)], Character = c })
.Select(x => new { x.Alphabet, Index = x.Alphabet.IndexOf(x.Character) })
.Select(x => new { x.Alphabet, Index = x.Index + shift })
.Select(x => new { x.Alphabet, Index = x.Index % x.Alphabet.Length })
.Select(x => x.Alphabet.ElementAt(x.Index))
.Aggregate(new StringBuilder(), (builder, character) => builder.Append(character))
.ToString();
Console.Write(encoded);
// encoded = "KHOOR ZRUOG 901"
Decoding is simply a case of inverting the shift.
Caesar cipher can be easier like this:
static char Encrypt(char ch, int code)
{
if (!char.IsLetter(ch))
{
return ch;
}
char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)(((ch + code - offset) % 26) + offset);
}
static string Encrypt(string input, int code)
{
return new string(input.ToCharArray().Select(ch => Encrypt(ch, code)).ToArray());
}
static string Decrypt(string input, int code)
{
return Encrypt(input, 26 - code);
}
const string TestCase = "Pack my box with five dozen liquor jugs.";
static void Main()
{
string str = TestCase;
Console.WriteLine(str);
str = Encrypt(str, 5);
Console.WriteLine("Encrypted: {0}", str);
str = Decrypt(str, 5);
Console.WriteLine("Decrypted: {0}", str);
Console.ReadKey();
}

Resources