我有一个字符串数组,我想获得字符串数组中特定元素中的字符数,我该怎么做? 像数组arr has = {“abc”,“bgfgh”,“gtddsffg”} 如果我使用
则为a.length;我将得到3是数组中的no.of元素
但我想要一种方法,当我在每个元素上应用时,如
for(int = 0; ; i++)
{
int t = a[i].length; //this method doesn't work
}
返回每个元素中的字符数 给定的例子必须是3,5和8
请回复?
答案 0 :(得分:3)
package stackoverflow.q_24933319;
public class FindLength {
public static void main(String[] args) {
String[] arr = {"abc","bgfgh","gtddsffg"};
System.out.println("Array size is: " + arr.length);
for(String s : arr) {
System.out.println("Value is " + s + ", length is " + s.length());
}
}
}
//Output:
//Array size is: 3
//Value is abc, length is 3
//Value is bgfgh, length is 5
//Value is gtddsffg, length is 8
答案 1 :(得分:2)
与数组不同,String
没有属性length
,但它有一个方法length()
,它返回String的长度(以Unicode代码为单位,请参阅JavaDoc )。
试试这个:a[i].length()
。
答案 2 :(得分:1)
我认为一个好主意是将字符数放入另一个表中。如果你愿意,你可以在for循环之外的每个数字上做一些其他的操作。
String [] input = {"aaaa", "sdasdwdas", "sd"};
int [] output = new int [input.length];
for (int i = 0; i < input.length; i++)
output[i] = input[i].length();
答案 3 :(得分:0)
我认为这段代码至少在其中一个功能中可以回答你的问题。
public int[] getEachLengthIndividually(String[] arr)
{
int[] retArray = new int[arr.length];
for(int i = 0; i < arr.length; i++)
{
String string = arr[i];
retArray[i] = string.length();
}
return retArray;
}
public int totalSize(String[] arr)
{
int totalSize = 0;
for(String string : arr)
{
totalSize += string.length();
}
return totalSize;
}
public static void main(String[] args)
{
String[] arr = {"abc", "bgfgh", "gtddsffg"};
int[] eachLengthIndividually = getEachLengthIndividually(arr);
int totalLength = getTotalLength(arr);
for(int i = 0; i < eachLengthIndividually.length; i++)
{
System.out.println("The string " + arr[i] + " at index " + i + " has length of " + eachLengthIndividually[i]);
}
System.out.println("The total length of all strings in the array is " + totalLength);
}