2017-01-17 33 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位」/「。如果您的問題解決了,請接受任何合適的答案 –

相關問題