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
}
}
Related
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;
i am trying to load textfield value in to mutable array using add object method but that value is not in string formate.i enter the array structure in below. thank you.
{
ItemUPC = rr001; ------->>>>>in this place
ItemUnits = "";
Itemcost = "";
}
i expected this structure
{
ItemUPC = "rr001"; ------->>>>>in this place
ItemUnits = "";
Itemcost = "";
}
thankyou
Try with this:
[NSString stringWithFormat:#"%#", yourtextField.text];
in both cases it IS actually a string. the problem is that NSLog() only shows the "" signs if it is an empty string or if there are some spaces within the string!
you can check it like this:
for (id object in yourArrayName) {
NSLog(#"%#", [object class]);
}
if the object IS a string it should say something like __NSCFConstantString.
I am developing an iOS app and one of the things I need to do it to go over URLs and replace the first protocol section with my own custom protocol.
How can I delete the first few characters of a NSString before the "://"?
So for example I need convert the following:
http://website.com --> cstp://website.com
ftp://website.com --> oftp://website.com
https://website.com --> ctcps://website.com
The main problem I face, is that I can't just delete the first 'x' number of characters from the URL string. I have to detect how many characters there are till the "://" characters are reached.
So how can I count how many characters there are from that start of the string to the "://" characters?
Once I know this, I can then simply do the following to delete the characters:
int counter = ... number of characters ...
NSString *newAddress = [webURL substringFromIndex:counter];
Thanks for your time, Dan.
http://website.com is a URL, and http is the scheme part of the URL. Instead of string manipulation I would recommend to use the
NSURLComponents class which is made exactly for this purpose: inspect, create and modify URLs:
NSString *originalURL = #"http://website.com";
NSURLComponents *urlcomp = [[NSURLComponents alloc] initWithString:originalURL];
if ([urlcomp.scheme isEqualToString:#"http"]) {
urlcomp.scheme = #"cstp";
} else if ([urlcomp.scheme isEqualToString:#"ftp"]) {
urlcomp.scheme = #"otfp";
}
// ... handle remaining cases ...
NSString *modifiedURL = [urlcomp string];
NSLog(#"%#", modifiedURL); // cstp://website.com
If the number of cases grows then a dictionary mapping is easier to
manage:
NSDictionary *schemesMapping = #{
#"http" : #"cstp",
#"ftp" : #"otfp"
#"https" : #"ctcps" };
NSURLComponents *urlcomp = [[NSURLComponents alloc] initWithString:originalURL];
NSString *newScheme = schemesMapping[urlcomp.scheme];
if (newScheme != nil) {
urlcomp.scheme = newScheme;
}
NSString *modifiedURL = [urlcomp string];
You can use:
NSRange range = [urlString rangeOfString:#"://"];
range.location will give you the first index from where the "://" starts and you can use it as:
NSString *newAddress = [urlString substringFromIndex:range.location];
and append your prefix:
NSString *finalAddress = [NSString stringWithFormat:#"%#%#", prefixString, newAddress];
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.
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