Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hi I have a problem with strings. I want to add :
NSString *termo = [NSString stringWithFormat:#"%#%#: %# ", #"~00000000:",nazwa, #".*"];
This .* is anything. How can I use it?
Your question is very unclear, however your comment "I have some string which I get from server. I want to parse this string with this" seems to suggest:
that you have a string obtained from somewhere;
this string should contain the text you have stored in the variable nazwa; and
you wish to find the text that follows whatever nazwa contains.
If this guess is correct then the following code fragment might help, it does not contain any checks you need to make to verify the input actually contains what you are looking for and is followed by something - check the documentation for the methods used to see what they return if they don't locate the text etc.:
// a string representing the input
NSString *theInput = #"The quick brown fox";
// nazwa - the text we are looking for
NSString *nazwa = #"quick";
// locate the text in the input
NSRange nazwaPosition = [theInput rangeOfString:nazwa];
// a range contains a location (offset) and a length, so
// adding these finds the offset of what follows
NSUInteger endofNazwa = nazwaPosition.location + nazwaPosition.length;
// extract what follows
NSString *afterNazwa = [theInput substringFromIndex:endofNazwa];
// display
NSLog(#"theInput '%#'\nnazwa '%#'\nafterNazwa '%#'", theInput, nazwa, afterNazwa);
This outputs:
theInput 'The quick brown fox'
nazwa 'quick'
afterNazwa ' brown fox'
HTH
.* is a regular expression that is used to match anything, but if you just want to see if an NSString isn't empty, you're better off doing something like this
![string isEqualToString:#""]
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Anyone have any idea to show large value in exponent form in objective?
e.g. 10000000000
What will the formula to show this number in exponent form.
This answer assumes you are asking about scientific e-notation.
If your goal is to convert the number 10000000000 to a string as 1e10 then use the e or E format specifier:
NSString *exponent = [NSString stringWithFormat:#"%e", 10000000000];
Use %E is you want a capital E instead of a lowercase e in the output.
And note that %e and %E can be formatted just like %f meaning you can specify the number of decimals, the total width, and whether leading spaces or zeros should be used as needed.
See the full documentation for printf.
Guessing: by "show" you mean convert to text format for display or printing.
If so then the two main ways to produce a textual representation for a numerical value are stringwithFormat: (& friends) and NSNumberFormatter.
The first of these provides a C printf-like facility. For example:
double val = 10000000000;
NSString *text = [NSString stringWithFormat:#"%g", val];
will set text to the string 1e+10. This example uses the %g format, there are others such as %f, and formatting such as the number of decimal places can be specified - for more details see the documentation.
The second provides an object-based facility. For example:
NSNumberFormatter *formatter = [NSNumberFormatter new];
formatter.numberStyle = NSNumberFormatterScientificStyle;
NSString *text = [formatter stringFromNumber:#(val)];
will set text to the string 1E10. There are other properties which can be set to control many aspects of the formatting, and NSNumberFormatter handles international differences in number formatting (like for those countries which use a comma (,) as the decimal fraction indicator rather then the point (.)). Again read the documentation.
HTH
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I am currently trying to make a simple craps app for the iPhone.
In the model I have a method:
-(NSString *)resultsOfRoll:(int)firstRoll :(int)secondRoll
{
NSString *results = #"";
NSArray *naturalNumbers = #[#7,#11];
NSArray *losingNumbers = #[#2, #3, #12];
NSArray *pointNumbers = #[#4,#5,#6,#8,#9,#10,#11];
int sum = firstRoll + secondRoll;
if(sum in naturalNumbers)
{
return #"You rolled a natural! You won";
}
return results
}
But I am getting an error. I am pretty new to Obj C and I haven't used much enumeration(If that is wrong please correct me) yet. Could someone let me know if I am initializing the loop correctly and how I can check to see if the sum (roll + roll) is in an array?
Also, does my method name look correct? I am coming from Java and these method sigs are still a little confusing for me.
if(sum in naturalNumbers) obviously isn't valid syntax. You're using something like 'for in' and with an int instead of an object.
What you want is:
if ([naturalNumbers containsObject:#(sum)]) {
Which asks the array if it contains an NSNumber instance containing the sum.
Your method doesn't name the second parameter, which is legal but not encouraged. It would be better as:
-(NSString *)resultsOfRoll:(int)firstRoll secondRoll:(int)secondRoll
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an array of items (for this excercise they are order line items), which are strings inserted line by line to an array. How can I display the contents of the array in a textview without the brackets or commas of the array for each line? I guess it would be along the lines of iterate through the array and for each object take the value, convert to a string and add a line break and add that string to a main mutable string and then set the textfield to the contents of the mutable string. But I would like to know how to iterate the array with code and insert the line breaks.
So, this outputs the values into a UITextField
NSArray *yourArray = [[NSArray alloc] initWithItems:#"A", #"B", #"C"];
NSMutableString *arrayValues = [[NSMutableString alloc] init];
for (uint i=0;[i<[yourArray count];i++)
{
NSString *myStr = [yourArray itemAtIndex:i];
[arrayValues append:myStr];
[arrayValues append:#"\n"];//insert a newline
}
yourTextField.value=arrayValues;
I think this does it, if not, can you explain "But I would like to know how to iterate the array with code and insert the line breaks." more?
How about this? If the elements of your array are strings as you say at the beginning of your post, this probably gets you what you want.
yourTextField.text = [yourArray componentsJoinedByString:#"\n"];
Each element in the array will have 'description' called on it during this joining process. NSStrings return themselves as their description, but if the elements of your array are a type that you created you could always consider overriding 'description' to get the format you want.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm quite new to NSString manipulation and don't have much experience at all of manipulating strings in any language really.
My problem is that I have a string that contains a lot of data, within this data is a name that I need to extract into a new NSString. EG:
NSString* dataString =#"randomdata12359123888585/name_john_randomdatawadapoawdk"
"/name_" always precede the data I need and "_" always follows it.
I have looked into things such as NSScanner but I'm not quite sure what the correct approach is or how to implement NSScanner.
Your string format is very well-defined (as you say, the name you are after is always preceded by "/name_" and always followed by "_"), and I suppose that the name ("john") hence cannot contain an underscore.
I'd therefore consider a simple regular expression, which is perfectly suited for this sort of problem:
NSString *regexPattern = #"^.*/name_(.*?)_.*$";
NSString *name = [dataString stringByReplacingOccurrencesOfString: regexPattern
withString: #"$1"
options: NSRegularExpressionSearch
range: NSMakeRange(0, dataString.length)];
In case you are not familiar with regular expressions, what is going on here is:
Begin at the beginning of the string (the "^")
Allow anything (".*") followed by "/name_"
Capture what follows (the parenthesis means "capture this")
In the parenthesis, allow anything (".*"), but make it as short as possible (the "?" after the "*")
It must be followed by an underscore and then allow anything that happens to be there up to the end of the string (the "$")
This will match the whole string, and when substituting the match (i.e., all of the string) with "$1", it will substitute the match with the substring included in the first (and only) parenthesis.
Result: It will produce a string that contains only the name. If the string does not have the correct format (i.e., no name between two underscores), then it will not change anything and return the full, original string.
It is a matter of coding style whether you prefer one approach over the other, but if you like regular expressions, then this approach is both clean, easy to understand and simple to maintain.
As I see it, any fragility in this is due to the data format, which looks suspiciously like something that depends on other "random" pieces of data, so whichever method you choose to parse that string, make sure you add some defensive tests to check the data format and alert you if unexpected strings begin to enter your data. This could be years from now, when you have forgotten everything about underscores, regexes and NSScanner.
-(void)separateString{
NSString* dataString =#"randomdata12359123888585/name_john_randomdatawadapoawdk";
NSArray *arr1 = [dataString componentsSeparatedByString:#"/"];
NSArray *arr2 = [[arr1 objectAtIndex:1] componentsSeparatedByString:#"_"];
NSLog(#"%# %#",arr1,arr2);
}
The output you get is
arr1= (
randomdata12359123888585,
"name_john_randomdatawadapoawdk"
)
arr2 = (
name,
john,
randomdatawadapoawdk
)
now you can access the name or whatever from the array index.
I managed to do this with NSScanner, however the array answer would work too so I've upvoted it.
The NSScanner code I used for anyone else facing a similar problem is:
-(void)formatName{
NSString *stringToSearch = _URLString; //url string is the long string we wish to search.
NSScanner *scanner = [NSScanner scannerWithString:stringToSearch];
[scanner scanUpToString:#"name_" intoString:nil]; // Scan all characters before name_
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:#"name_" intoString:nil]; // Scan the # character
if([scanner scanUpToString:#"_" intoString:&substring]) {
// If the space immediately followed the _, this will be skipped
_nameIwant = substring; //nameIwant is a property to store the name I scanned for
return;
}
}
}
i am new to cocoa sqlite in my app i am saving database in table with student data. when i am giving same name it is not accepting the name its fine, but when i giving space rather than name it accepting the spaces rather than any string. i used #"" to check if the name is empty or not , but my problem is it taking spaces..... so i want to avoid the spaces to save my data
Looking at the NSString documentation, it appears you need to use stringByTrimmingCharactersInSet:, to trim the whitespace from the string before saving it. Something like this should work:
// Remove whitespace
NSString *trimmedString = [enteredName stringByTrimmingCharactersInSet:whitespaceCharacterSet];
// Check if the string is empty
if(![trimmedString isEqualToString:#""])
{
// Save...
}