How to capture last 4 characters from NSString - ios

I am accepting an NSString of random size from a UITextField and passing it over to a method that I am creating that will capture only the last 4 characters entered in the string.
I have looked through NSString Class Reference library and the only real option I have found that looks like it will do what I want it to is
- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange
I have used this once before but with static parameters 'that do not change', But for this implementation I am wanting to use non static parameters that change depending on the size of the string coming in.
So far this is the method I have created which is being passed a NSString from an IBAction else where.
- (void)padString:(NSString *)funcString
{
NSString *myFormattedString = [NSString stringWithFormat:#"%04d",[funcString intValue]]; // if less than 4 then pad string
// NSLog(#"my formatedstring = %#", myFormattedString);
int stringLength = [myFormattedString length]; // captures length of string maybe I can use this on NSRange?
//NSRange MyOneRange = {0, 1}; //<<-------- should I use this? if so how?
}

Use the substringFromIndex method,
OBJ-C:
NSString *trimmedString=[string substringFromIndex:MAX((int)[string length]-4, 0)]; //in case string is less than 4 characters long.
SWIFT:
let trimmedString: String = (s as NSString).substringFromIndex(max(s.length-4,0))

Try This,
NSString *lastFourChar = [yourNewString substringFromIndex:[yourNewString length] - 4];

You can check this function in Swift 5:
func subString(from myString: NSString, length: Int) {
let myNSRange = NSRange(location: myString.length - length, length: length)
print(myString.substring(with: myNSRange))
}
subString(from: "Menaim solved the issue", length: 4) // Output: ssue

Related

how to convert uitextfield integer into string

I am new to iOS. I need to convert textfield integer value into string. I created textfield name as value1 and string as str1.
str1 = [NSString stringWithFormat:#"%d", value1];
By default, UITextField returns a NSString value.
So you can get any value like this :
NSString *str1 = value1.text;
As simple as that, but if you want to convert it to Int then,
int strInt = str1.intValue;
NSInteger strInteger = str1.integerValue;
If want to converts to a Double value,
double strDouble = str1.doubleValue;
CGFloat strCGFloat = str1.doubleValue;
And yes, if you don't need to perform anything on str1 then you shouldn't need to create an instance, you can directly convert it like this.
int strInt = value1.text.intValue;
NSInteger strInteger = value1.text.intValue;

Regex get string from string

I have NSString that contain this string :
c&&(b.signature=Rk(c));return ql(a,b)}
The RK can be any two chars.
I try to get the RK from the string with (RegexKitLit):
NSString *functionCode = [dataStr2 stringByMatching:#".signature=(.*?)\(" capture:1L];
and functionCode is always nil.Any idea what wrong?
Don't bother with regular expressions for this. If the format of the string is always the same then you can simply do:
NSString *dataStr2 = #"c&&(b.signature=Rk(c));return ql(a,b)}";
NSString *functionCode = [dataStr2 substringWithRange:NSMakeRange(16, 2)];
If the string is not quite so fixed then base it on the position of the =.
NSString *dataStr2 = #"c&&(b.signature=Rk(c));return ql(a,b)}";
NSRange equalRange = [dataStr2 rangeOfString:#"="];
NSString *functionCode = [dataStr2 substringWithRange:NSMakeRange(equalRange.location + equalRange.length, 2)];

Append to beginning of NSString method

I would like to append NSString A in front of NSString B. Is there a built in method to append to the beginning of a NSString instead of the end of the NSString?
I know that I can use stringWithFormat, but then what is the difference between using stringWithFormat and stringByAppendingString to add text to the end of a NSString?
If you can append to the end of a string, you can prepend to the beginning of the string.
Append
NSString* a = #"A";
NSString* b = #"B";
NSString* result = [a stringByAppendingString:b]; // Prints "AB"
Prepend
NSString* a = #"A";
NSString* b = #"B";
NSString* result = [b stringByAppendingString:a]; // Prints "BA"
Single line solution:
myString = [#"pretext" stringByAppendingString:myString];
You can use stringWithFormat too:
NSString *A = #"ThisIsStringA";
NSString *B = #"ThisIsStringB";
B = [NSString stringWithFormat:#"%#%#",A,B];
stringByAppendingString is an instance method of NSString,
stringWithFormat is a class method of the class NSString.
It's probably worth pointing out that there is no such thing as "appending one string onto another". NSString is immutable.
In every case, you are "creating a new string that consists of one string following another".
It doesn't matter that you put the newly created string back into the same variable.
You are never "adding text to the end of a string".
Here I’ve solution in Swift:
extension String {
// Add prefix only, if there is not such prefix into a string
mutating func addPrefixIfNeeded(_ prefixString: String?) {
guard let stringValue = prefixString, !self.hasPrefix(stringValue) else {
return
}
self = stringValue + self
}
// Add force full prefix, whether there is already such prefix into a string
mutating func addPrefix(_ prefixString: String?) {
guard let stringValue = prefixString else {
return
}
self = stringValue + self
}
}

How to make first letter uppercase in a UILabel?

I'm developing an iPhone app. In a label, I want to show an user's first letter of the name uppercase. How do I do that?
If there is only one word String, then use the method
-capitalized
let capitalizedString = myStr.capitalized // capitalizes every word
Otherwise, for multi word strings, you have to extract first character and make only that character upper case.
(2014-07-24: Currently accepted answer is not correct) The question is very specific: Make the first letter uppercase, leave the rest lowercase. Using capitalizedString produces a different result: “Capitalized String” instead of “Capitalized string”. There is another variant depending on the locale, which is capitalizedStringWithLocale, but it's not correct for spanish, right now it's using the same rules as in english, so this is how I'm doing it for spanish:
NSString *abc = #"this is test";
abc = [NSString stringWithFormat:#"%#%#",[[abc substringToIndex:1] uppercaseString],[abc substringFromIndex:1] ];
NSLog(#"abc = %#",abc);
In case someone is still interested in 2016, here is a Swift 3 extension:
extension String {
func capitalizedFirst() -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased() + rest.lowercased()
}
func capitalizedFirst(with: Locale?) -> String {
let first = self[self.startIndex ..< self.index(startIndex, offsetBy: 1)]
let rest = self[self.index(startIndex, offsetBy: 1) ..< self.endIndex]
return first.uppercased(with: with) + rest.lowercased(with: with)
}
}
Then you use it exactly as you would for the usual uppercased() or capitalized():
myString.capitalizedFirst() or myString.capitalizedFirst(with: Locale.current)
Simply
- (NSString *)capitalizeFirstLetterOnlyOfString:(NSString *)string{
NSMutableString *result = [string lowercaseString].mutableCopy;
[result replaceCharactersInRange:NSMakeRange(0, 1) withString:[[result substringToIndex:1] capitalizedString]];
return result;
}
This is for your NSString+Util category...
- (NSString *) capitalizedFirstLetter {
NSString *retVal;
if (self.length < 2) {
retVal = self.capitalizedString;
} else {
retVal = string(#"%#%#",[[self substringToIndex:1] uppercaseString],[self substringFromIndex:1]);
}
return retVal;
}
You can do that with NSString stringWithFormat, of course. I use this weirdness:
#define string(...) \
[NSString stringWithFormat:__VA_ARGS__]
As an extension to the accepted answer
capitalizedString is used for making uppercase letters .
NSString *capitalizedString = [myStr capitalizedString]; // capitalizes every word
But if you have many words in a string and wants to get only first character as upper case use the below solution
NSString *firstCapitalChar = [[string substringToIndex:1] capitalizedString];
NSString *capString = [string stringByReplacingCharactersInRange:NSMakeRange(0,1) withString: capString];
// extract first character and make only that character upper case.
here's a swift extension for it
extension NSString {
func capitalizeFirstLetter() -> NSString {
return self.length > 1 ?
self.substringToIndex(1).capitalizedString + self.substringFromIndex(1) :
self.capitalizedString
}
}
This is how it worked for me:
NSString *serverString = jsonObject[#"info"];
NSMutableString *textToDisplay = [NSMutableString stringWithFormat:#"%#", serverString];
[textToDisplay replaceCharactersInRange:NSMakeRange(0, 1) withString:[textToDisplay substringToIndex:1].capitalizedString];
cell.infoLabel.text = textToDisplay;
Hope it helps.
Swift:
let userName = "hard CODE"
yourLabel.text = userName.localizedUppercaseString
I recommend using this localised version of uppercase, since names are locale sensitive.

unichar* to NSString, get the length

I am trying to create an NSString object from a const unichar buffer where I don't know the length of the buffer.
I want to use the NSString stringWithCharacters: length: method to create the string (this seems to work), but please can you help me find out the length?
I have:
const unichar *c_emAdd = [... returns successfully from a C++ function...]
NSString *emAdd = [NSString stringWithCharacters:c_emAdd length = unicharLen];
Can anyone help me find out how to check what unicharLen is? I don't get this length passed back to me by the call to the C++ function, so I presume I'd need to iterate until I find a terminating character? Anyone have a code snippet to help? Thanks!
Is your char buffer null terminated?
Is it 16-bit unicode?
NSString *emAdd = [NSString stringWithFormat:#"%S", c_emAdd];
Your unichars should be null terminated so you when you reach two null bytes (a unichar = 0x0000) in the pointer you will know the length.
unsigned long long unistrlen(unichar *chars)
{
unsigned long long length = 0llu;
if(NULL == chars) return length;
while(NULL != chars[length])
length++;
return length;
}
//...
//Inside Some method or function
unichar chars[] = { 0x005A, 0x0065, 0x0062, 0x0072, 0x0061, 0x0000 };
NSString *string = [NSString stringWithCharacters:chars length:unistrlen(chars)];
NSLog(#"%#", string);
Or even simpler format with %S specifier

Resources