繁体   English   中英

如何遍历 Java 中的字符串?

[英]How can I iterate over a string in Java?

public static Boolean cmprStr( String s1, String s2 )
{
    // STUFF
}

我想遍历 s1 以确保 s1 中的每个字符都包含在 s2 中。

  for(char c: s1.toCharArray()){
     if(s2.indexOf(c) == -1){
           return false;
     }
  }
  return true;

假如说

  s1 = "aabb";
  s2 = "ccddaannbbss";

将返回真。

public static Boolean cmprStr( String s1, String s2 )
{
    for (int i = s1.length() - 1; i >= 0; --i) {
         if (s2.indexOf(s1.charAt(i)) == -1) {
             return Boolean.FALSE;
         }
    }
    return Boolean.TRUE;
}
length()

会给你一个字符串的长度

charAt( someIndex)

将为您提供给定 position 的字符,因此您可以迭代第一个字符串。

indexOf( achar )

会给你一个字符串中的字符,或者 -1 如果它不存在。 因此,您应该能够在第二个字符串中查找第一个字符串中的每个字符。

所有其他答案都是 O(n^2)。 这是使用Google Guava的一种时间线性方式(即 O(n)):

  public static boolean cmprStr(String s1, String s2) {
    Set<Character> desiredCharacters = Sets.newHashSet(Lists.charactersOf(s2));
    return Sets.difference(Sets.newHashSet(Lists.charactersOf(s1)), desiredCharacters).isEmpty();
  }
Set<Character> charsInS1 = new HashSet<Character>();
for (int i = 0; i < s1.length(); i++) {
  charsInS1.add(s1.charAt(i));
}
for (int i = 0; i < s2.length(); i++) {
  charsInS1.remove(s2.charAt(i));
}
return charsInS1.isEmpty();

这具有O(n+m)的复杂性 ...使用indexOf的答案具有O(n*m)的复杂性。 当然,它确实暂时使用了一些额外的 memory。

为什么不简单地使用“等于”方法?

Boolean b = s1.equals(s2);

Java 中的每个String也是一个CharSequence 因此,您可以使用简单的 for 循环轻松地遍历String

int n = s.length();
for (int i = 0; i < n; ++i) {
    char c = s.charAt(i);
    ...
}
// Here's some code I wrote to find CG ratio in a gene     
public double findCgRatio(String gene)
        {
            double cCount =0.0; 
            double gCount =0.0; 
            gene = gene.toLowerCase(); 
            for(char character : gene.toCharArray())
            {
                if(character == 'c')
                {
                    cCount++; 
                }
                else if(character == 'g')
                {
                    gCount++; 
                }

            }
            System.out.println("CG Ratio was :" + (cCount/gCount) );  
            return cCount/gCount;  // cgRatio 
        }

据我了解,这将是一个问题。

//for each character in s1
  //if s2 does not contain character return false

//return true

for(int i = 0; i < length s1; i++){
  if(!s2.contains(String.valueOf(s1.charAt(i)))){
    return false;
  }
}
return true;

这验证了 s1 中的每个字符都在 s2 中。 它不确认顺序,也不确认有多少,也不是equals方法。

递归:

public static Boolean cmprStr( String s1, String s2 )
{
  if(s1.length() == 0 )
  {
    return true; 
  }
  if(!s2.contains(s1.substring(0,1)))
  {
    return false;
  }
  return cmprStr(s1.substring(1), s2);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM