我想存储字符串的所有子字符串,例如:"car"
=> {"c","a","r","ca","ar","car"}
。
我想在数组中使用for
循环。下面的代码只在数组中存储c
,a
,r
。
我需要一个嵌套的for
循环来解决它吗?
String s = "car";
String[] arr;
for (int i = 0; i < s.length(); i++) {
arr[i] = s.charAt(i);
}
答案 0 :(得分:1)
这是你想要的吗?
for(int c = 0 ; c < string.length ; c++ )
{
for(int i = 1 ; i <= string.length - c ; i++ )
{
String sub = string.substring(c, c+i);
//do something with sub
}
}
答案 1 :(得分:0)
你可能想要这个:
String s="car";
List<String> list=new ArrayList<String>();
for(int ch=0;ch<s.length();ch++){
for(int pos=0;pos<s.length()-1;pos++)
{
if(pos+ch+1<=s.length())
{
list.add(s.substring(pos, pos+ch+1));
}
}
}
System.out.println(""+list);