2015-07-09 37 views
2

我想將句子(它是一個字符串)的一部分保存到另一個字符串中。Java中的子字符串 - 如何將句子分解並保存爲不同的字符串

例如:

的String =「通過1889年,中央電話交換運營商被稱作「你好-女童由於問候和電話之間的關聯」

欲保存「到1889年,中央電話交換運營商被稱爲」成一個字符串

「你好,女童因associatio在問候和電話之間「轉換成另一個。

如何做?

+1

什麼是拆分給定字符串的標準?以及被稱爲[空間]「hello-girls **」的空間會發生什麼變化? – Alp

+0

你想分割它的字符嗎?一定數量的字符?你想不止一次地這樣做?你想要嗎?當它到達某個特定的字符時將它分割?您應該查看分隔符。 – mgtemp

回答

2

使用下面的代碼

String s = " By 1889, central telephone exchange operators were known as 'hello-girls' due to the association between the greeting and the telephone "; 
    int index=s.indexOf("'"); 
    String s1=s.substring(0,index); 
    String s2=s.substring(index,s.length()-1); 
    System.out.println(s1); 
    System.out.println(s2); 

看到這個ideone https://ideone.com/iB5quw

+0

請參閱ideone的鏈接https://ideone.com/iB5quw –

1
String s = " By 1889, central telephone exchange operators " + 
      "were known as 'hello-girls' due to the association " + 
      "between the greeting and the telephone "; 

第一種方式:

String[] strings = s.split("as "); 

String first = strings[0] + "as"; 
// "By 1889, central telephone exchange operators were known as" 

String second = strings[1]; 
// "'hello-girls' due to the association between the greeting and the telephone" 

方式二:

String separator = " as "; 
int firstLength = s.indexOf(separator) + separator.length(); 

String first = s.substring(0, firstLength); 
// "By 1889, central telephone exchange operators were known as" 

String second = s.substring(firstLength); 
// "'hello-girls' due to the association between the greeting and the telephone" 
2

如果是因爲這個詞的'你好,女孩,你可以這樣做:

int index = s.indexOf("'hello-girls'")); 

String firstPart = s.substring(0, index); 
String secondPart = s.substring(index); 

注意,firstPart字符串將有一個空的空間結束。您可以通過更改上面的代碼輕鬆刪除它:

String firstPart = s.substring(0, index - 1); 
相關問題