How to extract substring from a string in ios? - nsstring

I know this is one of the most asked question , but I am not getting how to acually do this.
Here is my string ====> #"latitude - 51.50998000 , longitude - -0.13370000".
and I want to extract only the numeric values from it. How can this be achieved? Any ideas?

// Obtaining latitude string
NSString *locationString = #"latitude - 51.50998000 , longitude - -0.13370000";
NSRange latStringRange = NSMakeRange(11, 10);
NSString *latitudeSubstring = [locationString substringWithRange:latStringRange];
NSLog(#"Latitude substring is :- %#",latitudeSubstring);
//Obtaining longitude string
NSString *locString = #"latitude - 51.50998000 , longitude - -0.13370000";
NSRange longsStringRange = NSMakeRange(37, 10);
NSString *longSubstring = [locString substringWithRange:longsStringRange];
NSLog(#"Longitude substring is :- %#",longSubstring);

Not perfect solution but something to start with:
NSString *myString = #"latitude - 51.50998000 , longitude - -0.13370000";
/* Formatter is used to convert NSString to NSNumber */
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
/* Predicate is used to filter array, we need only NSString values with length > 2 */
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"length > 2"];
/* Character set is used to extract only -.0123456789 characters from string */
NSCharacterSet *cSet = [[NSCharacterSet characterSetWithCharactersInString:#"-.0123456789"] invertedSet];
/* Parse latitude and longitude values to NSArray, index 0 will be latitude and index 1 will be longitude */
NSArray *values = [[myString componentsSeparatedByCharactersInSet:cSet] filteredArrayUsingPredicate:predicate];
NSNumber *latitude = [formatter numberFromString:[values objectAtIndex:0]];
NSNumber *longitude = [formatter numberFromString:[values objectAtIndex:1]];
NSLog(#"lat: %f, long: %f", [latitude doubleValue], [longitude doubleValue]);

Related

how to make double from string

My user never value to a pop up and I add .0 at the end however once I convert the value to double the value is edited to only 2 and I need the value 2.0
if (pResult.Ok && !string.IsNullOrWhiteSpace(pResult.Text))
{
var test = pResult.Text + ".0";
double doub = Convert.ToDouble(test);
_settingsService.TimeOutIdentification = doub;
}
Please use following code to convert it
string str1 = String.Format("{0:F}", test);

Formatting NgbDate

I have a datepicker using NgbDate. I would like the format to spell out the month, hyphen, year. For example, August-2020. How can I format the following date this way?
effectiveDate = new NgbDate(date.year, date.month, date.day);
effectiveDate = effectiveDate.month.toString() + '-' +
effectiveDate.year.toString();
// the `effectiveDate` is of type `NgbDate`
effectiveDate = new NgbDate(date.year, date.month, date.day);
// you try to assign `string` to `NgbDate` which could work and it's very confusing
effectiveDate = effectiveDate.month.toString() + '-' +
effectiveDate.year.toString();
// instead it's better to create a variable for string value + string interpolation will make it easy to read
const formattedDate = `${effectiveDate.month}-${effectiveDate.year}`;
// or you can convert `NgbDate` into `Date` in the controller
this.jsDate = new Date(effectiveDate.year, effectiveDate.month - 1, effectiveDate.day);
// and use the `date` pipe in the component's HTML
jsDate | date: 'MM-yyyy'

Convert string start with 0 to 2 decimal place asp.net?

I have this string:
Dim value as String = "0.11209176170341301"
And tried to use this code to convert the string into decimal with two places:
Dim value as String = "0.11209176170341301"
Dim valueInDecimal As Decimal
If [Decimal].TryParse(value, valueInDecimal) Then
Console.WriteLine(valueInDecimal.ToString("0:0.#"))
End If
I get this result:
11209176170341301D
I need to get this:
0.11
What I'm doing wrong?
I want to get as result a decimal with two placesfrom the string value
You can use basic string operations also:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
decimal d = decimal.Parse(truncatedValue);
string s = d.ToString();
Console.Write(s);
Console.Read();
If you are only needed it as string then you can just truncate it as string then it will be easier like:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = parts[0] + "," + floatingPart;
Console.Write(truncatedValue);
Or even you do not convert '.' to ',' then it will be like this:
string value = "0.11209176170341301";
var parts = value.Split('.');
var floatingPart = parts[1].Substring(0, 2);
var truncatedValue = string.Join(".",parts[0],floatingPart);
Console.Write(truncatedValue);
Use Math.Round function
var x = "0.11209176170341301";
Console.Write(Math.Round(Convert.ToDecimal(x), 2));

UILabel detect line breaks

I am currently using a UILabel to display multiple lines of text. The line break most is set to NSLineBreakByWordWrapping so the the label automatically inserts line breaks. How can I detect where those line breaks are? Basically, I want to return a string with each \n break included.
Here is my work around for detecting line breaks inside UILabel
- (int)getLengthForString:(NSString *)str fromFrame:(CGRect)frame withFont:(UIFont *)font
{
int length = 1;
int lastSpace = 1;
NSString *cutText = [str substringToIndex:length];
CGSize textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
while (textSize.height <= frame.size.height)
{
NSRange range = NSMakeRange (length, 1);
if ([[str substringWithRange:range] isEqualToString:#" "])
{
lastSpace = length;
}
length++;
cutText = [str substringToIndex:length];
textSize = [cutText sizeWithFont:font constrainedToSize:CGSizeMake(frame.size.width, frame.size.height + 500)];
}
return lastSpace;
}
-(NSString*) getLinebreaksWithString:(NSString*)labelText forWidth:(CGFloat)lblWidth forPoint:(CGPoint)point
{
//Create Label
UILabel *label = [[UILabel alloc] init];
label.text = labelText;
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByWordWrapping;
//Set frame according to string
CGSize size = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(lblWidth, MAXFLOAT)
lineBreakMode:UILineBreakModeWordWrap];
[label setFrame:CGRectMake(point.x , point.y , size.width , size.height)];
//Add Label in current view
[self.view addSubview:label];
//Count the total number of lines for the Label which has NSLineBreakByWordWrapping line break mode
int numLines = (int)(label.frame.size.height/label.font.leading);
//Getting and dumping lines from text set on the Label
NSMutableArray *allLines = [[NSMutableArray alloc] init];
BOOL shouldLoop = YES;
while (shouldLoop)
{
//Getting length of the string from rect with font
int length = [self getLengthForString:labelText fromFrame:CGRectMake(point.x, point.y, size.width, size.height/numLines) withFont:label.font] + 1;
[allLines addObject:[labelText substringToIndex:length]];
labelText = [labelText substringFromIndex:length];
if(labelText.length<length)
shouldLoop = NO;
}
[allLines addObject:labelText];
//NSLog(#"\n\n%#\n",allLines);
return [allLines componentsJoinedByString:#"\n"];
}
How to use
NSString *labelText = #"We are what our thoughts have made us; so take care about what you think. Words are secondary. Thoughts live; they travel far.";
NSString *stringWithLineBreakChar = [self getLinebreaksWithString:labelText forWidth:200 forPoint:CGPointMake(15, 15)];
NSLog(#"\n\n%#",stringWithLineBreakChar);
You just need to set parameters required by getLinebreaksWithString and you will get a string with each "\n" break included.
OutPut
Here is my solution to this problem.
I iterate through all whitespace characters in the provided string, set substrings (from beginning to current whitespace) to my label and check the difference in the height. When the height changes I insert a new line character (simulates a line break).
func wordWrapFormattedStringFor(string: String) -> String {
// Save label state
let labelHidden = label.isHidden
let labelText = label.text
// Set text to current label and size it to fit the content
label.isHidden = true
label.text = string
label.sizeToFit()
label.layoutIfNeeded()
// Prepare array with indexes of all whitespace characters
let whitespaceIndexes: [String.Index] = {
let whitespacesSet = CharacterSet.whitespacesAndNewlines
var indexes: [String.Index] = []
string.unicodeScalars.enumerated().forEach { i, unicodeScalar in
if whitespacesSet.contains(unicodeScalar) {
let index = string.index(string.startIndex, offsetBy: i)
indexes.append(index)
}
}
// We want also the index after the last character so that when we make substrings later we include also the last word
// This index can only be used for substring to this index (not from or including, since it points to \0)
let index = string.index(string.startIndex, offsetBy: string.characters.count)
indexes.append(index)
return indexes
}()
var reformattedString = ""
let boundingSize = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude)
let attributes = [NSFontAttributeName: font]
var runningHeight: CGFloat?
var previousIndex: String.Index?
whitespaceIndexes.forEach { index in
let string = string.substring(to: index)
let stringHeight = string.boundingRect(with: boundingSize, options: .usesLineFragmentOrigin, attributes: attributes, context: nil).height
var newString: String = {
if let previousIndex = previousIndex {
return string.substring(from: previousIndex)
} else {
return string
}
}()
if runningHeight == nil {
runningHeight = stringHeight
}
if runningHeight! < stringHeight {
// Check that we can create a new index with offset of 1 and that newString does not contain only a whitespace (for example if there are multiple consecutive whitespaces)
if newString.characters.count > 1 {
let splitIndex = newString.index(newString.startIndex, offsetBy: 1)
// Insert a new line between the whitespace and rest of the string
newString.insert("\n", at: splitIndex)
}
}
reformattedString += newString
runningHeight = stringHeight
previousIndex = index
}
// Restore label
label.text = labelText
label.isHidden = labelHidden
return reformattedString
}
Image - Comparison of output string with label text.
This solution worked really well in my case, hope it helps.

Can someone show me how to display time + additional minutes in Objective C

Say the hour is 15:03.
Say variable minutesToAdd is 39
What's the code that will display 15:42 on a UILabel (current time + minutesToAdd)?
Here is some code, I dont check it in XCode (and its will not compiled just after copy/paste), but the idea is like I wrote below:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dc = [[[NSDateComponents alloc] init] autorelease];
dc.minute = 39;
NSDate *srcDate = NSDate(15:03); // Create date here
NSDate *resultDate = [calendar dateByAddingComponents:dc toDate:srcDate]; // Here is your new date

Resources