How to remove starting 0's in uitextfield text in iphone sdk - iphone

Code Snippet:
NSString *tempStr = self.consumerNumber.text;
if ([tempStr hasPrefix:#"0"] && [tempStr length] > 1) {
tempStr = [tempStr substringFromIndex:1];
[self.consumerNumbers addObject:tempStr];>
}
I tried those things and removing only one zero. how to remove more then one zero
Output :001600240321
Expected result :1600240321
Any help really appreciated
Thanks in advance !!!!!

Try to use this one
NSString *stringWithZeroes = #"001600240321";
NSString *cleanedString = [stringWithZeroes stringByReplacingOccurrencesOfString:#"^0+" withString:#"" options:NSRegularExpressionSearch range:NSMakeRange(0, stringWithZeroes.length)];
NSLog(#"Clean String %#",cleanedString);
Clean String 1600240321

convert string to int value and re-assign that value to string,
NSString *cleanString = [NSString stringWithFormat:#"%d", [string intValue]];
o/p:-1600240321

You can add a recursive function that is called until the string begin by something else than a 0 :
-(NSString*)removeZerosFromString:(NSString *)anyString
{
if ([anyString hasPrefix:#"0"] && [anyString length] > 1)
{
return [self removeZerosFromString:[anyString substringFromIndex:1]];
}
else
return anyString;
}
so you just call in your case :
NSString *tempStr = [self removeZerosFromString:#"000903123981000"];

NSString *str = #"001600240321";
NSString *newStr = [#([str integerValue]) stringValue];
If the NSString contains numbers only.
Other wise use this:
-(NSString *)stringByRemovingStartingZeros:(NSString *)string
{
NSString *newString = string;
NSInteger count = 0;
for(int i=0; i<[string length]; i++)
{
if([[NSString stringWithFormat:#"%c",[string characterAtIndex:i]] isEqualToString:#"0"])
{
newString = [newString stringByReplacingCharactersInRange:NSMakeRange(i-count, 1) withString:#""];
count++;
}
else
{
break;
}
}
return newString;
}
Simply call this method:-
NSString *stringWithZeroes = #"0000000016909tthghfghf";
NSLog(#"%#", [self stringByRemovingStartingZeros:stringWithZeroes]);
OutPut: 16909tthghfghf

Try the `stringByReplacingOccurrencesOfString´ methode like this:
NSString *new = [old stringByReplacingOccurrencesOfString: #"0" withString:#""];
SORRY: This doesn't help you due to more "0" in the middle part of your string!

Related

All Pairs of 0 remove from NSString in Objective-C

I want to remove all occurrence of 0 pairs before appearing any digit(1-9) from NSString
if 000001234000 required 01234000
if 0000123400 required 123400
if 012340000 required 012340000
if 00000012 required 12
Can anyone help ? thanks.
Perhaps not the most elegant solution (but only trims leading '00'):
- (NSString *)trimLeadingDoubleZerosFrom:(NSString *)str {
if (str.length > 1 ) {
if ([[str substringWithRange:NSMakeRange(0, 2)] isEqualToString:#"00"]) {
return [self trimLeadingDoubleZerosFrom:[str substringFromIndex:2]];
}
}
return str;
}
Seems to work for your examples:
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"000001234000"]);// returns 01234000
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"0000123400"]); // returns 123400
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"012340000"]); // returns 012340000
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"00000012"]); // returns 12
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"12"]); // returns 12
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"02"]); // returns 02
NSLog(#"%#", [self trimLeadingDoubleZerosFrom:#"2"]); // returns 2
NSString *MyString = #"00000123050060007";
NSString *NewString = [self RemovePairOfZero:MyString];
NSLog(#"OUTPUT:: %#", NewString);
- (NSString *)RemovePairOfZero:(NSString *)Param
{
if ([Param length] > 1 )
{
if ([[Param substringWithRange:NSMakeRange(0, 2)] isEqualToString:#"00"])
{
return [self RemovePairOfZero:[Param substringFromIndex:2]];
}
}
return Param;
}
//2013-09-24 13:15:58.527 Test[1584:907] OUTPUT:: 0123050060007
NSString* a = #"00000123";
while ([a hasPrefix:#"00"]) {
a = [a stringByReplacingCharactersInRange:NSMakeRange(0, 2) withString:#""];
}
You can try using stringByreplacingOccurancesOfString:#"00" withString:#""
NSString *s= #"00000123";
NSLog(#"%#",s);
s = [s stringByReplacingOccurrencesOfString:#"00" withString:#"."];
NSLog(#"%#",s);
Try this one..
That can be done by simply replacing #"00" with #""
NSString *string = #"00000123";
string = [string stringByReplacingOccurrencesOfString:#"00" withString:#""];
Hope that helps!

How can I verify if a String has a null value?

sorry but i'm still struggling to make this code working. It works if with a 2 digits number but it crashes with a single digit number. How can I verify if the NSString *secDigit has a value or is null. I hope my question is clear. Thanks in advance.
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", [deposit text]];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
char firstChar = [firstThird characterAtIndex:0];
char secChar = [firstThird characterAtIndex:1];
NSString *firstDigit = [NSString stringWithFormat:#"%c",firstChar];
NSString *secDigit = [NSString stringWithFormat:#"%c", secChar];
NSLog(#" i'm %#", firstDigit);
NSLog(#" i'm %#", secDigit);
if ([firstDigit isEqualToString: #"1"]) {
firstDigit=#"wet";
NSLog(#"wet");
}
if ([firstDigit isEqualToString: #"2"]) {
firstDigit=#"wet";
NSLog(#"snow");
}
if ([firstDigit isEqualToString: #"3"]) {
firstDigit=#"wet";
NSLog(#"ice");
}
if ([secDigit isEqualToString: #"1"]) {
secDigit=#"wet";
NSLog(#"wet");
}
if ([secDigit isEqualToString: #"2"]) {
secDigit=#"snow";
NSLog(#"snow");
}
if ([secDigit isEqualToString: #"3"]) {
secDigit=#"ice";
NSLog(#"ice");
}
thanks to all of you..... here my code (working now):
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", [deposit text]];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
char firstChar = [firstThird characterAtIndex:0];
NSString *firstDigit = [NSString stringWithFormat:#"%c",firstChar];
NSLog(#" i'm %#", firstDigit);
if ([firstDigit isEqualToString: #"1"]) {
firstDigit=#"wet";
NSLog(#"wet");
}
if ([firstDigit isEqualToString: #"2"]) {
firstDigit=#"wet";
NSLog(#"snow");
}
if ([firstDigit isEqualToString: #"3"]) {
firstDigit=#"wet";
NSLog(#"ice");
}
if ([firstThird length] >1) {
char secChar = [firstThird characterAtIndex:1];
NSString *secDigit = [NSString stringWithFormat:#"%c", secChar];
if ([secDigit isEqualToString: #"1"]) {
secDigit=#"wet";
NSLog(#"wet");
}
if ([secDigit isEqualToString: #"2"]) {
secDigit=#"snow";
NSLog(#"snow");
}
if ([secDigit isEqualToString: #"3"]) {
secDigit=#"ice";
NSLog(#"ice");
}
}
I guess you code crashes in this line:
char secChar = [firstThird characterAtIndex:1];
This is because you try to access a character outside of the string bounds. You need to guard against this by checking the length of the string first:
if ([firstThird count] > 1) {
// String has 2 or more characters, do all the stuff that involves
// a second character.
char secChar = [firstThird characterAtIndex:1];
NSString *secDigit = [NSString stringWithFormat:#"%c", secChar];
if ([secDigit isEqualToString: #"1"]) {
secDigit=#"wet";
NSLog(#"wet");
}
}
But I'd also like to recommend to not use an NSString here, as you already have a char. Just do something like this:
if ([firstThird count] > 1) {
// String has 2 or more characters, do all the stuff that involves
// a second character.
char secChar = [firstThird characterAtIndex:1];
if (secChar == '1') {
secDigit=#"wet";
NSLog(#"wet");
}
}
I think this is what you are looking for:
char secChar;
if(firstThird.length > 1)
{
secChar = [firstThird characterAtIndex:1];
}
According to this
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
NSString "Raises an NSRangeException if index lies beyond the end of the receiver"
So, your code:
char secChar = [firstThird characterAtIndex:1];
Is the problem (you should see that in the debugger Console)
Check the length first with
if ([firstThird length] < 2) {
// handle the case where it is one digit
}
You can check number of characters in a string using NSString length. and modify your code
as
NSString *depositOverTotalRwy = [NSString stringWithFormat:#"%#", #"23"];
NSArray *components = [depositOverTotalRwy
componentsSeparatedByString:#"/"];
NSString *firstThird = [components objectAtIndex:0];
unichar firstChar;
unichar secChar;
if([firstThird length]>1){
firstChar = [firstThird characterAtIndex:0];
secChar = [firstThird characterAtIndex:1];
} else {
firstChar = [firstThird characterAtIndex:0];
secChar = 0;
}
switch (firstChar) {
case '1': /* Do your stuff*/break;
case '2': /* Do your stuff*/break;
case '3': /* Do your stuff*/break;
default:
break;
}
switch (secChar) {
case '1': /* Do your stuff*/break;
case '2': /* Do your stuff*/break;
case '3': /* Do your stuff*/break;
default:
break;
}
you can use unichar instead of char. And can perform check in switch statements.
If you use char, a casting is done from unichar to char and for some characters you may lose actual value. So it is safe to use unichar...
If you want to convert unichar to string simply code
NSString * stringChar = [NSString StringWithFormat:#"%C",unicharVariable];
Thats it ...

how to remove particular words from strings?

I have an NSString *str, having value #"I like Programming and gaming."
I have to remove "I" "like" & "and" from my string so it should look like as "Programming gaming"
How can I do this, any Idea?
NSString *newString = #"I like Programming and gaming.";
NSString *newString1 = [newString stringByReplacingOccurrencesOfString:#"I" withString:#""];
NSString *newString12 = [newString1 stringByReplacingOccurrencesOfString:#"like" withString:#""];
NSString *final = [newString12 stringByReplacingOccurrencesOfString:#"and" withString:#""];
Assigned to wrong string variable edited now it is fine
NSLog(#"%#",final);
output : Programming gaming
NSString * newString = [#"I like Programming and gaming." stringByReplacingOccurrencesOfString:#"I" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"like" withString:#""];
newString = [newString stringByReplacingOccurrencesOfString:#"and" withString:#""];
NSLog(#"%#", newString);
More efficient and maintainable than doing a bunch of stringByReplacing... calls in series:
NSSet* badWords = [NSSet setWithObjects:#"I", #"like", #"and", nil];
NSString* str = #"I like Programming and gaming.";
NSString* result = nil;
NSArray* parts = [str componentsSeparatedByString:#" "];
for (NSString* part in parts) {
if (! [badWords containsObject: part]) {
if (! result) {
//initialize result
result = part;
}
else {
//append to the result
result = [NSString stringWithFormat:#"%# %#", result, part];
}
}
}
It is an old question, but I'd like to show my solution:
NSArray* badWords = #[#"the", #"in", #"and", #"&",#"by"];
NSMutableString* mString = [NSMutableString stringWithString:str];
for (NSString* string in badWords) {
mString = [[mString stringByReplacingOccurrencesOfString:string withString:#""] mutableCopy];
}
return [NSString stringWithString:mString];
Make a mutable copy of your string (or initialize it as NSMutableString) and then use replaceOccurrencesOfString:withString:options:range: to replace a given string with #"" (empty string).

How to count '\n' in an UITextView

I got a headache trying to count returns (\n) in my UITextView. As you'll soon realise, I'm a bloody beginner and here is my theory of what I've come up with, but there are many gaps...
- (IBAction)countReturns:(id)sender {
int returns;
while ((textView = getchar()) != endOfString [if there is such a thing?])
{
if (textView = getchar()) == '\n') {
returns++;
}
}
NSString *newText = [[NSString alloc] initWithFormat:#"Number of returns: %d", returns];
numberReturns.text = newText;
[newText release];
}
I checked other questions on here, but people are usually (in my eyes) lost in some details which I don't understand. Any help would be very much appreciated! Thanks for your patience.
You can simply
UITextView *theview; //remove this line, and change future theview to your veiw
NSString *thestring; //for storing a string from your view
int returnint = 0;
thestring = [NSString stringWithFormat:#"%#",[theview text]];
for (int temp = 0; temp < [thestring length]; temp++){ //run through the string
if ([thestring characterAtIndex: temp] == '\n')
returnint++;
}
NSArray *newlines = [textView.text componentsSeparatedByString:#"\n"];
int returns = ([newlines count]-1)
Should work. Keep in mind this isn't such a great idea if you have a gia-normous string, but it's quick, dirty and easy to implement.
there are a lot of ways to do that. Here is one:
NSString *str = #"FooBar\n\nBaz...\n\nABC\n";
NSString *tmpStr = [str stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSInteger count = [str length] - [tmpStr length];
NSLog(#"Count: %d", count);

NSString range of string at occurrence

i'm trying to build a function that will tell me the range of a string at an occurrence.
For example if I had the string "hello, hello, hello", I want to know the range of hello at it's, lets say, third occurrence.
I've tried building this simple function, but it doesn't work.
Note - the top functions were constructed at an earlier date and work fine.
Any help appreciated.
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim toChar:(NSUInteger)toCharacterIndex {
if (toCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = 0; i <= toCharacterIndex; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSString *)stringByTrimmingString:(NSString *)stringToTrim fromChar:(NSUInteger)fromCharacterIndex {
if (fromCharacterIndex > [stringToTrim length]) return #"";
NSString *devString = [[[NSString alloc] init] autorelease];
for (int i = (fromCharacterIndex+1); i <= [stringToTrim length]; i++) {
devString = [NSString stringWithFormat:#"%#%#", devString, [NSString stringWithFormat:#"%c", [stringToTrim characterAtIndex:(i-1)]]];
}
return devString;
[devString release];
}
- (NSRange)rangeOfString:(NSString *)substring inString:(NSString *)string atOccurence:(int)occurence {
NSString *trimmedString = [inString copy]; //We start with the whole string.
NSUInteger len, loc, oldLength;
len = 0;
loc = 0;
NSRange tempRange = [string rangeOfString:substring];
len = tempRange.length;
loc = tempRange.location;
for (int i = 0; i != occurence; i++) {
NSUInteger endOfWord = len+loc;
trimmedString = [self stringByTrimmingString:trimmedString fromChar:endOfWord];
oldLength += [[self stringByTrimmingString:trimmedString toChar:endOfWord] length];
NSRange tmp = [trimmedString rangeOfString:substring];
len = tmp.length;
loc = tmp.location + oldLength;
}
NSRange returnRange = NSMakeRange(loc, len);
return returnRange;
}
Instead of trimming the string a bunch of times (slow), just use rangeOfString:options:range:, which searches only within the range passed as its third argument. See Apple's documentation.
So try:
- (NSRange)rangeOfString:(NSString *)substring
inString:(NSString *)string
atOccurence:(int)occurence
{
int currentOccurence = 0;
NSRange rangeToSearchWithin = NSMakeRange(0, string.length);
while (YES)
{
currentOccurence++;
NSRange searchResult = [string rangeOfString: substring
options: NULL
range: rangeToSearchWithin];
if (searchResult.location == NSNotFound)
{
return searchResult;
}
if (currentOccurence == occurence)
{
return searchResult;
}
int newLocationToStartAt = searchResult.location + searchResult.length;
rangeToSearchWithin = NSMakeRange(newLocationToStartAt, string.length - newLocationToStartAt);
}
}
You need to rework the whole code. While it may seem to work, it's poor coding and plain wrong, like permanently reassigning the same variable, initializing but reassigning one line later, releasing after returning (which will never work).
For your question: Just use rangeOfString:options:range:, and do this the appropriate number of times while just incrementing the starting point.