2017-01-17 37 views
-1

我需要获得两个不同长度的不同注册号的位置,并重新使用我获得的位置。如何在java中使用数组或其他技术的字符串位置

我需要为目标的部分是哪里MS字符留

我需要的方式,我可以告诉系统知道regNo包含MS和它做一些事情。

regNo : BCS/MS/13/09/0001 
regNo : BCOM/MS/09/0149 

if (the position 5 and position 6 of regNo equals to S){ 
    .. do s.thing 
    } 
or 

if (the part after/there is MS){ 
    ... do something 
} 

回答

0

只是为了总结有几个选项:

  • String#contains - 如果字符串包含char值的指定序列将显示。重要的是要记住 - contains忽略位置。 "MS".contains("MS")"ABS/MS/".contains("MS")都返回true。如果您需要检查“MS”是否位于字符串contains中的某个位置可能不是最佳选择。
  • String#indexOf - 返回此字符串中第一次出现指定子字符串的索引。
  • String#matches - 判断此字符串是否与给定的正则表达式匹配。这对于验证字符串的格式非常有用,特别是如果子字符串的位置可能有所不同。在你的情况下,“MS”可能在不同的位置。因此,我们可以使用类似这样:System.out.println("BCS/MS/13/09/0001".matches("[A-Z]+\\/MS.*"));或多个特定System.out.println("BCOM/MS/09/0149".matches("[A-Z]{3,4}\\/MS(?:\\)"));first regex explanationsecond regex
+0

谢谢,这更清楚了先生@Anton – user3518835

0

使用正则表达式

final String msg = "BCS/MS/13/09/0001"; 
System.out.println((msg.split("/")[1])); 
+0

什么将在这里印刷:?的System.out.println((msg.split( “/”)[1])); – user3518835

+0

你会得到字符串MS –

0

我用:

String msg = "BCS/MS/13/09/0001"; 
if (ms.contains("MS")) 
    { 
    Do . sothing 
    } 

和它的工作

0
String str1 = "BCS/MS/13/09/0001"; 
int pos1= str1.indexOf("MS"); 
String str2 = "BCOM/MS/09/0149"; 
int pos2= str2.indexOf("MS"); 

现在你可以使用值POS1和POS2任何需要的地方。

因为你可以像下面更具体的搜索,

String str1 = "BCS/MS/13/09/0001"; 
int pos1= str1.indexOf("/MS/")+1; 
String str2 = "BCOM/MS/09/0149"; 
int pos2= str2.indexOf("/MS/")+1; 
+0

Thanksz @ Anil,这个+1意味着什么? – user3518835

+0

str1.indexOf(“/ MS /”)将在字符串“/ MS /”中给出第一个字母的位置,即:“/”。但是我们仅需要“MS”的位置,所以我在/ MS /“ –

+0

中添加了1位”/“。如果您的问题解决了,请接受任何合适的答案 –

相关问题