How to separate the sentence into words? - ios

split the sentence into words with out using "componentsSeparatedByString:"
my word is "This is a well known simple"
I wrote like this separtedWord=[noteTextView.text componentsSeparatedByString: #" "];
but I want with out using componentsSeparatedByString.please help me

I have wrote following logic. Created two properties like this :
#property(nonatomic,strong) NSMutableArray *strings;
#property(nonatomic,strong) NSMutableString *tempString;
Wrote business logic like this :
NSString *sampleString = #"This is a well known simple";
self.tempString = [[NSMutableString alloc] init];
self.strings = [[NSMutableArray alloc] init];
for( int i = 0; i < sampleString.length; i++ )
{
unichar currentChar = [sampleString characterAtIndex:i];
NSString *character = [NSString stringWithCharacters:&currentChar length:1];
if( currentChar != ' ' )
{
[self.tempString appendString:character];
if( i == sampleString.length - 1 )
{
[self addString:self.tempString];
}
}
else
{
[self addString:self.tempString];
[self.tempString setString:#""];
}
}
NSLog(#"Array Of String = %#",self.strings);
- (void)addString:(NSString *)string
{
[self.strings addObject:[NSString stringWithString:string]];
}
2014-07-24 15:23:22.306 ViemoPlayer[1834:70b] Array Of String = (
This,
is,
a,
well,
known,
simple
)
Hope this helps.

Convert the NSString into a char array.
Loop through the array and an if statement inside, and keep appending the charecters inside the charArray into a local NSMutableString using
for(int i =0;i<[myCharArray count];i++){
NSMutableString *teststring;
[teststring appendString:[myCharArray objectAtIndex : i]];
if([myCharArray objectAtIndex] == " "){
NSLog(teststring);
teststring = #""; //emptying the testString when we get a space
}
}
That should do it

Related

How to convert string into an IP Address?

I am using a function to adding . after every three characters inside the string. But how can i remove "0" in front of number.
-(NSString *)formatStringAsIpAddress:(NSString*)MacAddressWithoutColon
{
NSMutableString *macAddressWithColon = [NSMutableString new];
for (NSUInteger i = 0; i < [MacAddressWithoutColon length]; i++)
{
if (i > 0 && i % 3 == 0)
[macAddressWithColon appendString:#"."];
unichar c = [MacAddressWithoutColon characterAtIndex:i];
[macAddressWithColon appendString:[[NSString alloc] initWithCharacters:&c length:1]];
}
return macAddressWithColon;
}
If i have ip address 010.000.001.016
How can i set it up like 10.0.1.16? and if i have ip address 192.168.001.001? how to remove front 0's from IP address ?
What I would suggest:
NSString *ipAddress = #"010.000.001.016";
Split string into array of substrings:
NSArray *ipAddressComponents = [myString componentsSeparatedByString:#"."];
Run through the array with for loop and convert each to a int representation:
for(int i = 0; i < ipAddressComponents.count;i++)
{
[ipAddressComponents objectAtIndex:i] = [NSString stringWithFormat:#"%d",[[ipAddressComponents objectAtIndex:i]intValue]];
}
Join the array back into a string
NSString *newIpAddress = [ipAddressComponents componentsJoinedByString:#"."];
This should result into getting an IP address: 10.0.1.16
You can use string function and get your expected output with the help of componentsSeparatedByString and componentsJoinedByString functions.
Use below method for the same:
-(NSString*)removeZeroPrefix:(NSString*)aStrIP{
NSMutableArray *subStringArray = [[NSMutableArray alloc] init];
NSArray *arrayOfSubString = [aStrIP componentsSeparatedByString:#"."];
for (NSString *aSingleString in arrayOfSubString)
{
[subStringArray addObject:[NSNumber numberWithInteger:[aSingleString integerValue]]];
}
return [subStringArray componentsJoinedByString:#"."];
}
Usage :
[self removeZeroPrefix:#"010.000.001.016"];
[self removeZeroPrefix:#"192.168.001.001"];
Output :
Printing description of aStrIP:
10.0.1.16
Printing description of aStrIP:
192.168.1.1
hope this will helps!
In Swift
let ip = "0125.052.000.10"
let split = ip.components(separatedBy: ".")
for number in split {
if let isNumber = Int(number){
print(isNumber) // add this isNumber into array which is shows without initial zeros.
}
}
Finally join created array as String with dot Component

Appending zeros to the end of an NSString?

I am having trouble with some code. I narrowed it down to this problem: first of all, reverseString and 2 are both NSMutableStrings _input1 and _input2 are NSStrings, i'm trying to add zeros to the smallest string but it's not working correctly, this is what I got. reverseString is #"123" and reverseString2 is #"34567".
//they get initialized back into the original strings
_input1=reversedString;
_input2=reversedString2;
//appends 0 to the shortest value
while ([_input1 length]>[_input2 length]){
_input2=[_input2 stringByAppendingString:#"0"];
_length=[_input1 length];
}
while ([_input1 length]<[_input2 length]){
_input1=[_input1 stringByAppendingString:#"0"];
_length=[_input2 length];
}
//converts the string to an NSArray
for (int i=0; i <([_input1 length]); i++) {
NSString *TempStr = [_input1 substringWithRange:NSMakeRange(i, 1)];
[one addObject:[TempStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
for (int i=0; i <([_input2 length]); i++) {
NSString *TempStr2 = [_input2 substringWithRange:NSMakeRange(i, 1)];
[two addObject:[TempStr2 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
Now I noticed that when it goes through this loop, the smallest one, _input1, gets set to #"" instead of adding zeros to the end. This is within a class, by the way.
This is also an error I receive:
objc[2291]: Method cache corrupted. This may be a message to an invalid object, or a memory error somewhere else.
objc[2291]: receiver 0x100300830, SEL 0x7fff8a689779, isa 0x7fff727b8bd0, cache 0x7fff727b8be0, buckets 0x7fff89b9b09c, mask 0x1, occupied 0x0, wrap bucket 0x7fff89b9b09c
objc[2291]: receiver 0 bytes, buckets 0 bytes
objc[2291]: selector 'length'
(lldb)
Just try with following code
if([_input1 length] > [_input2 length])
{
for (int i = 0 ; i < [_input1 length] - [_input2 length] ; i ++)
_input2 = [_input2 stringByAppendingString:#"0"];
}
else
{
for (int i = 0 ; i < [_input2 length] - [_input1 length] ; i ++)
_input1 = [_input1 stringByAppendingString:#"0"];
}
Try like this:-
NSString *input1=#"123";
NSString * input2=#"34567";
NSMutableArray *one=[NSMutableArray array];
NSMutableArray *two=[NSMutableArray array];
//appends 0 to the shortest value
while ([input1 length]>[input2 length]){
input2=[input2 stringByAppendingString:#"0"];
//length=[input1 length];
}
while ([input1 length]<[input2 length]){
input1=[input1 stringByAppendingString:#"0"];
// length=[input2 length];
}
for (int i=0; i <([input1 length]); i++) {
NSString *TempStr = [input1 substringWithRange:NSMakeRange(i, 1)];
[one addObject:[TempStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"%ld",[one count]);
for (int i=0; i <([input2 length]); i++) {
NSString *TempStr2 = [input2 substringWithRange:NSMakeRange(i, 1)];
[two addObject:[TempStr2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"%ld",[two count]);
Well your requirements are not very clear, but here's a cleaner version of the code you proposed
NSString *string1 = #"foo";
NSString *string2 = #"foobar";
// Compute the desired length
NSUInteger length = MAX(string1.length, string2.length);
// We will pad using this string
NSString *paddingString = #"0";
// Pad both strings to the same length
string1 = [string1 stringByPaddingToLength:length withString:paddingString startingAtIndex:0];
string2 = [string2 stringByPaddingToLength:length withString:paddingString startingAtIndex:0];
// Build two arrays containing the characters, percent escaped
NSMutableArray *charactersArray1 = [NSMutableArray arrayWithCapacity:string1.length];
NSMutableArray *charactersArray2 = [NSMutableArray arrayWithCapacity:string2.length];
for (NSInteger i = 0; i < string1.length; i++) {
[charactersArray1 addObject:[[string1 substringWithRange:(NSRange){ i, 1 }] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[charactersArray2 addObject:[[string2 substringWithRange:(NSRange){ i, 1 }] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
NSLog(#"String 1: %#\nString 2: %#", charactersArray1, charactersArray2);
The result will be
String 1: [ f, o, o, 0, 0, 0 ]
String 2: [ f, o, o, b, a, r ]
I figured out my problem, _input1 and _input2 were bad pointers and i had to fix it, sorry for all the confusion, in the end i got my code to work!

How to retrieve values from two Mutablearrays and store them in MutableDictionary with keys as an array?

I have 3 NSMutableArrays k,names,numbers
k array contains {a,b,c,d,e,.....}
names array contains {apple,bag,banana,car,cat,dall,elephant,.....}
numbers array contains {100,200,300,400,500,600,700,...}
All the 3 arrays are dynamic here.
I want to add names[],numbers[] to NSMutableDictionary with k[] as key array..
My output should be like this when i pint that dictionary
a
apple 100
b
bag 200
banana 300
c
car 400
cat 500
d
dall 600
e
elephant 700
Could somebody help me.
thank you.
NSMutableDictionary *result = [NSMutableDictionary new];
for(int i = 0; i<k.count; i++){
unichar letter = [k objectAtIndex:i]; //I'm assuming you have chars in your k array,
// if not, you have to format it here
NSString* name = [names objectAtIndex:i];
if([[name characterAtIndex:0] isEqual:letter]){
NSString *objectToInsert = [NSString stringWithFormat:#"%#: %#", #"name", [numbers objectAtIndex:i]];
[result setObject:objectToInsert forKey:letter];
}
}
You can probably optimize this more, but it should work ;)
Try with following code
NSMutableDictionary *mydic = [[NSMutableDictionary alloc] init];
For(int k = 0; k < firstArray.count ; k++)
{
NSPredicate *pred =[NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", [firstArray objectAtIndex:k]];
NSArray *filteredArr = [MySecodArray filteredArrayUsingPredicate:pred];
NSString *myString = #"";
for (int t = 0 ; t < filteredArr.count ; t ++)
{
myString = [MyThirdArray objectAtIndex:[MySecodArray indexOfObject:[filteredArr objectAtIndex:t]]];
myString = [[filteredArr objectAtIndex:t] stringByAppendingString:myString];
[mydic setValue: myString forKey:[firstArray objectAtIndex:k]];
myString = #"";
}
}
NSLog(#"%#", myDic);
You can do like This,I am assuming nameArry and NumberArray count is same-->
try This code
NSSMutableDictionary *finalDictionary = [[NSSmutableDictionary alloc]init];
for(int i=0;i<k.count;i++)
{
NSString *alphaBet = [k objectAtIndex:i];
//initialize array here
NSMutableArray *insideDictArray = [[NSMutableArray alloc]init];
for(int j=0;j<nameArray.count;j++)
{
NSString *name = [nameArray objectAtIndex:j];
if([name hasPreffix:alphabet])
{
//get Number String
NSString *numberForName = [numberArray objectAtIndex:j];
//Now Concate Number and Name
NSString *concateString = [name stringByAppendingFormat:#"
%#",numberForName];
//Put this in Array we just intialized outside of secondLoop
[insideDictArray addObject:concateString];
}
}
//Now Add array to finalDictionary
[finalDictionary addObject:insideDictArray forKey:alphabet];
}
OutPut Will Be like this i hope :
finalDictionary =
{
a = [aple 100];
b = [bag 200,banana 300];
.
.
}

Create string based on characters expected

I would like to create a string based on the number of characters passed in. Each character passed in will be a "X". So for example, if the length passed in is 5, then the string created should be
NSString *testString=#"XXXXX";
if it is 2 then it would be
NSString *testString=#"XX";
Can anyone tell me what the most efficient way to do this would be?
Thank you!
If you know the maximum length is some reasonable number then you could do something simple like this:
- (NSString *)xString:(NSUInteger)length {
static NSString *xs = #"XXXXXXXXXXXXXXXXXXXXXXXXXXX";
return [xs substringToIndex:length];
}
NSString *str = [self xString:5]; // str will be #"XXXXX";
If you pass in too large of a length, the app will crash - add more Xs to xs.
This approach is more efficient than building up an NSMutableString but it does make an assumption about the maximum length you might need.
- (NSString *)stringOf:(NSString *)str times:(NSInteger)count
{
NSMutableString *targ = [[NSMutableString alloc] initWithCapacity:count];
for (int i=0; i < count; i++)
{
[targ appendString:str];
}
return targ;
}
and
[self stringOf:#"X" times:4];
note that initWithCapacity: (in performance manner) better than init. But I guess that's all for efficiency.
The way I would do it is
NSMutableString *xString = [[NSMutableString alloc] init];
while ( int i = 0; i < testString.length; i++ ) {
[xString appendString:#"X"];
i++;
}
NSUInteger aLength. // assume this is the argument
NSMutableString *xStr = [NSMutableString stringWithCapacity: aLength];
for ( NSUInteger i = 0; i < aLength; i++ ) {
[xStr appendFormat:#"X"];
}
The following will do what you ask in one call:
NSString *result = [#"" stringByPaddingToLength:numberOfCharsWanted
withString:characterToRepeat
startingAtIndex:0];
where numberOfCharsWanted is an NSUInteger and characterToRepeat is an NSString containing the character.

Reversing a string in iOS [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am writing code which should reverse a string. When I run the following code it throws an error:
- (NSString*) reversingName:(NSString *)myNameText
{
NSString *result;
int len = [myNameText length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len;i>0;i--)
{
[reverseName appendFormat:[NSString stringWithFormat:#"%c",[myNameText characterAtIndex:i]]];
}
result = reverseName;
return result;
}
The for loop line should be as follows:
for(int i=len-1;i>=0;i--)
So your method should be
- (NSString*) reversingName:(NSString *)myNameText
{
int len = [myNameText length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len-1;i>=0;i--)
{
[reverseName appendString:[NSString stringWithFormat:#"%c",[myNameText characterAtIndex:i]]];
}
return [reverseName autorelease];
}
I thought I'd throw another version out there in case anyone's interested.. personally, I like the cleaner approach using NSMutableString but if performance is the highest priority this one is faster:
- (NSString *)reverseString:(NSString *)input {
NSUInteger len = [input length];
unichar *buffer = malloc(len * sizeof(unichar));
if (buffer == nil) return nil; // error!
[input getCharacters:buffer];
// reverse string; only need to loop through first half
for (NSUInteger stPos=0, endPos=len-1; stPos < len/2; stPos++, endPos--) {
unichar temp = buffer[stPos];
buffer[stPos] = buffer[endPos];
buffer[endPos] = temp;
}
return [[NSString alloc] initWithCharactersNoCopy:buffer length:len freeWhenDone:YES];
}
I also wrote a quick test as well to compare this with the more traditional NSMutableString method (which I also included below):
// test reversing a really large string
NSMutableString *string = [NSMutableString new];
for (int i = 0; i < 10000000; i++) {
int digit = i % 10;
[string appendFormat:#"%d", digit];
}
NSTimeInterval startTime = [[NSDate date] timeIntervalSince1970];
NSString *reverse = [self reverseString:string];
NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSince1970] - startTime;
NSLog(#"reversed in %f secs", elapsedTime);
Results were:
using NSMutableString method (below) - "reversed in 3.720631 secs"
using unichar *buffer method (above) - "reversed in 0.032604 secs"
Just for reference, here's the NSMutableString method used for this comparison:
- (NSString *)reverseString:(NSString *)input {
NSUInteger len = [input length];
NSMutableString *result = [[NSMutableString alloc] initWithCapacity:len];
for (int i = len - 1; i >= 0; i--) {
[result appendFormat:#"%c", [input characterAtIndex:i]];
}
return result;
}
(NOTE: I don't have enough reputation points yet to vote or comment on answers so I'd appreciate if anyone could vote on this answer for me. I've been a long time reader but now want to start contributing more!)
try this sample code :
NSString *name = #"abcdefghi" ;
int len = [name length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len-1;i>=0;i--)
{
[reverseName appendFormat:[NSString stringWithFormat:#"%c",[name characterAtIndex:i]]];
}
NSLog(#"%#",reverseName);
Reverse a String in Swift 2.0:
let string = "This is a test string."
let characters = string.characters
let reversedCharacters = characters.reverse()
let reversedString = String(reversedCharacters)
The short way :
String("This is a test string.".characters.reverse())
OR
let string = "This is a test string."
let array = Array(string)
let reversedArray = array.reverse()
let reversedString = String(reversedArray)
The short way :
String(Array("This is a test string.").reverse())

Resources