2017-02-14 84 views
-2

在這我需要接受用戶推定的句子,並在豬拉丁文中打印出來。 (我也有不需要的幾個進口,而是我離開他們時,我從其他程序中複製類和幹線)如何在字符串數組中分別訪問每個字符?

import static java.lang.System.*; 
import java.util.*; 
import java.lang.Math; 
public class Pig_latin 
{ 
    public static void main(String[]args) 
    { 

    String sentence; 

    out.print("Enter a complete sentence: "); 
    Scanner sc = new Scanner(System.in); 
    sentence=sc.nextLine(); 

我在這裏創造的空間的字符串數組和分裂。 唯一的問題是,現在每個單詞都在它自己的對象中。

String s1[]=sentence.split(" "); 

因爲我分開,我不知道的方式來訪問每個字符將其移動到年底或添加「AY」字樣。

for(int x=0;x<s1.length;x++) 
    { 

    } 
} 
} 
+0

's1 [x]'是您正在尋找的。 –

回答

1

繼承人一個簡單的方法來獲取每個字符在java中的字符串。 String.charAt(index)在指定的索引處獲取當前字符。

public static void main(String[] args) { 

     String getMyCharacters = "Hello World"; 

     for(int i = 0; i < getMyCharacters.length();i++) 
     { 
      System.out.print(getMyCharacters.charAt(i)); 
     } 

} 

output: Hello World 

而這是當你將每個單詞分成它自己的字符串時如何得到字符的一種方法。

String[] splitted = getMyCharacters.split(" "); 


for(int j = 0; j < splitted.length; j++) 
{ 
    System.out.println("\nCurrent word:" + splitted[j]); 
    for(int y = 0; y < splitted[j].length(); y++) 
    { 
     System.out.println(splitted[j].charAt(y)); 
    } 
} 

output: 
Current word:Hello 
H 
e 
l 
l 
o 

Current word:World 
W 
o 
r 
l 
d 
+0

謝謝,這正是我需要的! – TimeWinder23

0

您可以參考該陣列中的每個元素與s1[x],x是陣列S1的指數,因此說你正在尋找了數組的第x個元素。

for(int x=0;x<s1.length;x++) 
{ 
    System.out.println(s1[x]); 
} 
相關問題