嗨,生物学家,这里有一点编码背景。我的目标是能够输入一串字符和代码,以便能够告诉我它们出现了多少次以及在字符串中的哪个位置。 所以我将输入一个字符串,我想要字符串中 sq 和 tq 的位置和丰度。位置是第一个字符,例如 njnsqjjfl sq 将位于位置 4。
这是我到目前为止的想法(可能非常错误)
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'sq')}
counter++;})
string S = "...";
int counter =0;
for(int i=0; i<s.length; i++){
if(s.charAt (i) == 'tq')}
counter++;})
任何意见都会有帮助,谢谢
最佳答案
因此,您可以在代码中多次出现“sq”和“tq”,这样您就可以有 2 个数组列表来分别保存这两个数组(或者一个数组列表将它们保存在一起)。
ArrayList<Integer>sqLocation = new ArrayList<>();
ArrayList<Integer>tqLocation = new ArrayList<>();
for(int i =0;i<s.length()-1;i++){
if(s.charAt(i)=='s' && s.charAt(i+1)=='q'){
sqLocation.add(i);
}
else if(s.charAt(i)=='t' && s.charAt(i+1)=='q'){
tqLocation.add(i);
}
}
System.out.println("No. of times sq occurs = "+sqLocation.size());
System.out.println("Locations ="+sqLocation);
System.out.println("No. of times tq occurs = "+tqLocation.size());
System.out.println("Locations ="+tqLocation);
关于java - 字符串中字符的位置和重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37717435/