2010-04-22 102 views
0

如何找到字符串內的子字符串,然後在找到它時記住並刪除它。在字符串內部找到子字符串

例:

select * from (select a.iid_organizacijske_enote, 
     a.sifra_organizacijske_enote "Sifra OE", 
     a.naziv_organizacijske_enote "Naziv OE", 
     a.tip_organizacijske_enote "Tip OE" 

我想進去 「」 所有的字,所以

  • Sifra OE
  • Naziv OE
  • TIP OE

和返回

select * from (select a.iid_organizacijske_enote, 
     a.sifra_organizacijske_enote, 
     a.naziv_organizacijske_enote, 
     a.tip_organizacijske_enote 

我嘗試用正則表達式,indexOf()但沒有一個好的工作

+1

請注意,只是說一些不起作用通常不會很有幫助... http://blogs.msdn.com/oldnewthing/archive/2010/04/21/9999675.aspx – Joey 2010-04-22 09:41:35

回答

1

考慮在捕獲組中使用正則表達式。使用Java的Matcher類,您可以找到第一個匹配項,然後使用replaceFirst(String)。

- 編輯 -

例子(沒有有效的長期投入):

String in = "hello \"there\", \"friend!\""; 
Pattern p = Pattern.compile("\\\"([^\"]*)\\\""); 
Matcher m = p.matcher(in); 
while(m.find()){ 
    System.out.println(m.group(1)); 
    in = m.replaceFirst(""); 
    m = p.matcher(in); 
} 
System.out.println(in); 
+0

也許你有任何例子嗎? – senzacionale 2010-04-22 09:46:15

3

String.replace(..)

替換此字符串與指定的文字替換序列字面目標序列匹配的每個子字符串。替換從字符串開始到結束,例如,用字符串「aaa」中的「b」替換「aa」將導致「ba」而不是「ab」。

str = str.replace(wordToRemove, ""); 

如果你不提前知道的話,你可以使用regex version

str = str.replaceAll("\"[^\"]+\"", ""); 

這意味着,所有的字符串開始,除非報價與行情結束,因爲任何字符在它們之間,將被替換爲空字符串。

+0

thx求助Bozho – senzacionale 2010-04-22 11:25:24

1

我試圖創造功能如下 - 它的做工精細,並返回輸出你想

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Program p = new Program(); 
      string s = p.mystring("select * from (select a.iid_organizacijske_enote, a.sifra_organizacijske_enote 'Sifra OE', " 
     +"a.naziv_organizacijske_enote 'Naziv OE', "+ 
     "a.tip_organizacijske_enote 'Tip OE'"); 
     } 


     public string mystring(string s) 
     { 
      if (s.IndexOf("'") > 0) 
      { 
       string test = s.Substring(0, s.IndexOf("'")); 
       s = s.Replace(test+"'", ""); 

       s = s.Remove(0, s.IndexOf("'") + 1); 
       test = test.Replace("'", ""); 
       test = test + s; 
       return mystring(test); 
      } 
      else 
      { 
       return s; 
      } 
     } 
    } 
} 
+0

老闆!他把這個問題標記爲java,爲什麼在c#中回答。在你得到downvotes之前刪除。 – 2010-04-22 10:20:39

+0

我知道這個函數在java中也能正常工作 – 2010-04-22 10:24:03

+0

thx for help pranay – senzacionale 2010-04-22 11:25:08

0

最好&優化的代碼是在這裏:

public static void main(String[] args){ 
    int j =0; 
    boolean substr = true; 
    String mainStr = "abcdefgh"; 
    String ipStr = "efg"; 
    for(int i=0 ; i < mainStr.length();i++){ 
     if(j<ipStr.length() && mainStr.charAt(i)==ipStr.charAt(j)){ 
      j++; 
     }    
    } 
    if(j>=0 && j !=ipStr.length()){ 
     substr = false; 
    } 
    System.out.println("its a substring:"+substr); 
}