[英]How do i access each character individually in a string array?
In this i need to take in a user imputed sentence and print it out in pig-latin.在这个过程中,我需要输入一个用户输入的句子并用猪拉丁语打印出来。 (also i have several imports that aren't needed but I left them in when i copied the class and main lines from another program)
(我也有几个不需要的导入,但是当我从另一个程序复制类和主线时,我把它们留在了)
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();
Here i am creating the string array and splitting at the spaces.在这里,我正在创建字符串数组并在空格处拆分。 The only problem with this is that now each word is in its own object.
唯一的问题是现在每个单词都在它自己的对象中。
String s1[]=sentence.split(" ");
Because I've separated the words I don't know of a way to access each character to move them to the end or add "ay".因为我已经将单词分开了,所以我不知道如何访问每个字符以将它们移到末尾或添加“ay”。
for(int x=0;x<s1.length;x++)
{
}
}
}
Heres a simple way of how you can get each character in a string in java.这是如何在java中获取字符串中每个字符的简单方法。
String.charAt(index)
gets the current character at the index specified. 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
And this is one way of how you get the characters when you split each word into its own string.这是将每个单词拆分为自己的字符串时获取字符的一种方式。
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
You can refer each element of the array with s1[x]
, x is the index of the array s1, thereby saying you are looking up the xth element of the array.您可以使用
s1[x]
引用数组的每个元素,x 是数组 s1 的索引,从而表示您正在查找数组的第 x 个元素。
for(int x=0;x<s1.length;x++)
{
System.out.println(s1[x]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.