对不起,我是swift的新手。我想用字符串计算目标字符。但我不知道该怎么做。对我有什么好的建议吗?谢谢。
let string = "hello\nNice to meet you.\nMy name is Leo.\n" //I want to get 3
答案 0 :(得分:1)
如果您只想要换行字符,那么您可以对字符串的字符使用过滤器:
let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let count = string.characters.filter { $0 == "\n" }.count
print(count)
按预期输出3。
答案 1 :(得分:0)
另一种方法是使用 import java.util.ArrayList;
public class TestingJava {
public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
// If vector has [1, 2, 3]
// returned vector should be [1, 2, 4]
// 123 + 1 = 124
int total = 0;
// O(n)
for(Integer i: a){
total = 10*total + i;
}
total += 1;
int last_dig = total%10;
a.set((a.size()-1), last_dig);
// O(n**2)
while (a.get(0) == 0){
a.remove(0);
}
return a;
}
public static void main(String[] args) {
ArrayList<Integer> a1 = new ArrayList<>();
a1.add(0);
a1.add(1);
a1.add(2);
a1.add(3);
TestingJava c = new TestingJava();
System.out.println(c.plusOne(a1));
// Should output [1, 2, 4]. Should NOT output [0, 1, 2, 4]
}
}
方法拆分行:
components(separatedBy
或多功能考虑各种换行符
let string = "hello\nNice to meet you.\nMy name is Leo.\n"
let lineCounter = string.components(separatedBy: "\n").count - 1
由于尾随换行符,结果为4.要忽略尾随的新行,您必须减少结果。