Replace <br> in an NSString with a new line - ios

I have an NSString like this
NSString *string = #"textTextTextTextText<br>textTextTextText<br>TextTextText"
I want to set this NSString to be the text of my UICell with a new line on each tag found on the string. How could I do that?
I've tried this, without success:
cell.textLabel.text = [[text componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#"<br>"];

How about:
string = [string stringByReplacingOccurrencesOfString: #"<br>" withString: #"\n"]
or, if you're using Swift Strings
var string = "textTextTextTextText<br>textTextTextText<br>TextTextText"
string = Array(string).reduce("") {$0 + ($1 == "<br>" ? "\n" : $1)}

NSString * result =
[string stringByReplacingOccurrencesOfString:#"<br>" withString:#"\n"];

SWIFT 5:
If you are using Swift string (you can transform your NSString to String):
var string = "line1<br>line2<br>line3"
string = string..replacingOccurrences(of: "<br>", with: "\n"))

Related

Get position of NSString in string - iOS

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];

How to remove double quotes and brackets from NSString

I have string in this from ["658681","655917","655904"]i want to change this string in this form 658681,655917,655904 how it can be changed? below is my code of string
- (IBAction)Searchbtn:(id)sender {
NSData *data=[NSJSONSerialization dataWithJSONObject:getmessageIDArray options:kNilOptions error:nil];
_finalIDStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"the final ID Str==%#",_finalIDStr);
}
Use following code:
NSCharacterSet *unwantedChars = [NSCharacterSet characterSetWithCharactersInString:#"\"[]"];
NSString *requiredString = [[_finalIDStr componentsSeparatedByCharactersInSet:unwantedChars] componentsJoinedByString: #""];
It's efficient and effective way to remove as many characters from your string in one single line..
this will do it in swift
var stringwithoutquotes = string1.stringByReplacingOccurrencesOfString("\"", withString: "")
var removebracket1 = stringwithoutquotes.stringByReplacingOccurrencesOfString("[", withString: "")
var removebracket2 = removebracket1.stringByReplacingOccurrencesOfString("]", withString: "")
or you could do the entire thing in one line
var string2 = string.stringByReplacingOccurrencesOfString("\"", withString: "").stringByReplacingOccurrencesOfString("[", withString: "").stringByReplacingOccurrencesOfString("]", withString: "")
Here is another cleaner option in swift
var string = "\"hello[]" // string starts as "hello[]
var badchar: NSCharacterSet = NSCharacterSet(charactersInString: "\"[]")
var cleanedstring: NSString = (string.componentsSeparatedByCharactersInSet(badchar) as NSArray).componentsJoinedByString("")
//cleanedstring prints as "hello"
Swift 3:
let string = "\"hello[]" // string starts as "hello[]
let badchar = CharacterSet(charactersIn: "\"[]")
let cleanedstring = string.components(separatedBy: badchar).joined()
//cleanedstring prints as "hello"
Swift 4 (String Array)
I wanted to convert String Array into String text to be placed in TextView:
FROM
["horse","cat","dog"]
TO
horse
cat
dog
var stringArray = ["horse","cat","dog"]
var stringArrayCleaned = stringArray.description.replacingOccurrences(of: "\"", with: "").replacingOccurrences(of: ",", with: "\n").replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "").replacingOccurrences(of: " ", with: "")
print(stringArrayCleaned)
You can try :
[[[_finalIDStr stringByReplacingOccurrencesOfString:#"\"" withString:#""] stringByReplacingOccurrencesOfString:#"[" withString:#""] stringByReplacingOccurrencesOfString:#"]" withString:#""];
I know this is an old question, but in case someone is still looking for answer.. I achieved this in swift using joined(separator:) see: apple documentation
var stringArray = ["alice","bob","cindy"]
print(stringArray.joined(separator: ","))
// this will print: alice,bob,cindy
NSString *str = ["658681","655917","655904"];
NSCharacterSet *cs = [NSCharacterSet characterSetWithCharactersInString:#"\"[]"];
str = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:#""];

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)];

How to identify and remove newline and white spaces?

I am making an nsmutable array by separating a string by component it is causing a lot of new line and white spaces to be inserted in the array how to identify and remove them?
for (int i=0;i<contentsOfFile.count; i++)
{
if(!([[contentsOfFile objectAtIndex:i]isEqual:#"\n"]||[[contentsOfFile objectAtIndex:i]isEqual:#""]))
[arrayToBereturned addObject:[contentsOfFile objectAtIndex:i]];
}
this code which i am using cannot identify all new line charectors
thanks
To remove all extra space and \n from your string-
NSString* result = [yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
than prepare your contentsOfFile Array.
If you want an array without whitespace:
NSString *string = #"Hello, World!";
NSCharacterSet *separator = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *stringComponents = [string componentsSeparatedByCharactersInSet:separator];
stringByTrimmingCharachersInSet: only removes desired characters from the end and the beginning of the string. To remove all occurences you should use stringByReplacingOccurrencesOfString:
Swift 5 version
let string = "Hello, stack overflow!"
let components = string.components(separatedBy: .whitespacesAndNewlines)
print(components) // prints ["Hello,", "stack", "overflow!"]
Also regarding string.replacingOccurrences
let string = " Hello, stack overflow ! "
let noSpacingsString = string.replacingOccurrences(of: " ", with: "")
print(components) // prints "Hello,stackoverflow!"

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.

Resources