English 中文(简体)
如何将NSString拆分为组件?
原标题:How do you split NSString into component parts?

在Xcode中,如果我有一个NSString包含一个数字,即@“12345”,我如何将其拆分为一个表示组成部分的数组,即“1”、“2”、“3”、“4”、“5”。。。NSString对象上有一个componentsSeparatedByString,但在这种情况下没有分隔符。。。

最佳回答

看起来characterAtIndex:可以做到这一点,但这会返回一个unichar,它不是NSObject派生的数据类型,因此不能直接放入数组中。您需要为每个unichar构造一个新的字符串。

一个更简单的解决方案是使用具有1个字符范围的substringWithRange:。通过一个简单的for(int i=0;i<;[myString length];i++)循环运行字符串,将每个1个字符的范围添加到NSMutableArray中。

问题回答

NSString有一个现成的成员函数可以做到这一点:

NSString* foo = @"safgafsfhsdhdfs/gfdgdsgsdg/gdfsgsdgsd";
NSArray* stringComponents = [foo componentsSeparatedByString:@"/"];

NSString已经是其组件的数组,如果组件是指单个字符。使用[string length]获取字符串的长度,使用[string characterAtIndex:]

如果你真的需要一个只有一个字符的字符串对象数组,你必须自己创建这个数组。使用for循环遍历字符串中的字符,使用[NSString stringWithFormat:]创建一个带有单个字符的新字符串,并将其添加到数组中。但这通常是没有必要的。

在您的情况下,由于没有分隔符,您必须通过

- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange

或者这个

- (unichar)characterAtIndex:(NSUInteger) index inside a loop.

这是我目前唯一的看法。

不知道这是否适用于您想要做的事情,但是:

const char *foo = [myString UTF8String]
char third_character = foo[2];

请务必阅读UTF8String上的文档





相关问题
How to change out-of-focus text selection color in Xcode?

Okay, I ll bite. I ve got really pleasant code/window colors set up in Xcode. Ordinarily, my selection color is very visible. When I am doing a project search and iterating through the results, ...

Iphone NSTimer Issue

Hi I am new to objective c. I am trying to make an app for iphone. I have a button on my view, and the click on which the function playSound is called. This is working properly. It does plays the ...

Include a .txt file in a .h in C++?

I have a number of places where I need to re-use some template code. Many classes need these items In a .h could I do something like: #include <xxx.txt> and place all of this code in the ....

Iterating over string/strlen with umlauted characters

This is a follow-up to my previous question . I succeeded in implementing the algorithm for checking umlauted characters. The next problem comes from iterating over all characters in a string. I do ...

Xcode open two editor windows with same file

Is it possible to open the same file in two separate windows in Xcode. I can open a file in one window and the same file in the main Xcode editor window, but I wanted two separate fulltime editor ...

Forcing code signing refresh in Xcode

In our environment, we share resources across multiple projects and platforms. When building for iPhone, only a subset of those resources are needed. Since that subset is still considerable, we have ...