Objective-C中的字符串操作 [英] String Manipulation in Objective-C

查看:84
本文介绍了Objective-C中的字符串操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

掌握了如何在Objective-C中获取和写入变量的知识,现在是时候学习如何对它们进行更多有用的操作了!现在,我主要是想弄清楚字符串操作是如何工作的.特别是,我正在寻找以下功能:

Gotten a hold on how to fetch and write to variables in Objective-C, now it's time to learn how to do something more useful with them! Right now, I'm primarily trying to figure out how string manipulation works. In particular, I'm looking for the following functions:

  • 串联
  • 查找字符串的长度(尤其是多字节/UTF-8字符串;我对东亚语言进行了大量工作)
  • 仅提取字符串的一部分(例如,从"abcfoobarxyz"中提取"foobar")
  • 在字符串中搜索(请参见上面的示例)
  • 更改大小写(大写,小写,标题很简单)
  • 爆炸/隐喻字符串(例如,以逗号分隔的列表创建和获取信息)
  • 在字符串中查找/替换
  • 可能可用的任何其他通常有用的字符串函数

推荐答案

示例: 串联:

- (NSString*) concatenateString:(NSString*)stringA withString:(NSString*)stringB
{  
    NSString *finalString = [NSString stringWithFormat:@"%@%@", stringA,
                                                       stringB];
    return finalString;
}
// The advantage of this method is that it is simple to put text between the
// two strings (e.g. Put a "-" replace %@%@ by %@ - %@ and that will put a
// dash between stringA and stringB

字符串长度:

- (int) stringLength:(NSString*)string
{
    return [string length];
    //Not sure for east-asian languages, but works fine usually
}

从字符串中删除文本:

- (NSString*)remove:(NSString*)textToRemove fromString:(NSString*)input
{
   return [input stringByReplacingOccurrencesOfString:textToRemove
                                           withString:@""];
}

大写/小写/标题大写:

Uppercase / Lowercase / Titlecase:

- (NSString*)uppercase:(NSString*)stringToUppercase
{
   return [stringToUppercase uppercaseString];
}

- (NSString*)lowercase:(NSString*)stringToLowercase
{
   return [stringToLowercase lowercaseString];
}

- (NSString*)titlecase:(NSString*)stringToTitleCase
{
   return [stringToTitleCase capitalizedString];
}

查找/替换

- (NSString*)findInString:(NSString*)string
        replaceWithString:(NSString*)stringToReplaceWith
{
   return [input stringByReplacingOccurrencesOfString:string
                                           withString:stringToReplaceWith];
}

我希望这会有所帮助!

PS:别忘了查看文档,而Google是您的朋友.祝你好运

PS: Don't forget to check the documentation, and Google is your friend. Good luck

这篇关于Objective-C中的字符串操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆