【问题标题】:Compare two strings one shifted by a position比较两个字符串,其中一个偏移了一个位置
【发布时间】:2012-06-12 04:48:23
【问题描述】:

我有这两个字符串:

String s1 = "hello"; 
String s2 ="_hello";

当我比较它们时,我希望为这些字符串返回true(第二个字符串移动了一个位置)。

我应该使用哪种String 操作方法?谁能给我一个提示?

【问题讨论】:

  • 这两个字符串是什么结果?
  • 为什么不只是s2.equals('_' + s1)
  • 问号前不要使用任何标点符号。

标签: java string string-matching


【解决方案1】:

你可以使用String类的contains()

String s1 = "hello";
String s2 ="_hello";

if(s2.contains(s1))
   //true

你也可以使用subString()

s2= s2.subString(1);
if(s2.equalsIgnoreCase(s1))
   //true

是的,你也可以使用indexOf()

if(s2.indexOf(s1)>-1)
   //true

【讨论】:

  • 如果它被偏移的事实很重要,也可以考虑围绕 indexOf() 构建一个测试。
【解决方案2】:

你应该使用 indexOf 方法:

int index=s2.indexOf(s1);

if(index ==-1) // s1 is not present into s2.

else index 是 s2 中匹配 s1 的第一个字符的索引。例如:

String s1 = "hello"; String s2 ="_hello";

索引将为 1。

【讨论】:

    【解决方案3】:

    我还没有为 android 编程,所以对它持保留态度,但看看 String.indexOf()。我相信 Android 是基于 Java 的,所以这应该会有所帮助。

    【讨论】:

      猜你喜欢
      • 2017-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      相关资源
      最近更新 更多