input: statement
output: sta tat ate tem eme men ent
[基本上每个输出的长度基于第二个数组的长度]这里3
这就是我的尝试:
public class Stringg {
public static void main(String[] args)
{
char[] array1 ={'a','c','t','i','a','n','c','e'};
char[] array2 ={'a','n','c'};
System.out.println(array1.length);
System.out.println(array2.length);
String Str ="";
for (int i = 0; i < array1.length-array2.length; i++)
{
for (int j = i; j < array1.length-array2.length; j++)
{
System.out.print(array1[j]);
}
}
}
}
输出结果为:
8
3
actiactiatiaiaa
答案 0 :(得分:-1)
这是一个“正常工作”计划:
package com.example;
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("input: ");
String sourceString = scanner.next();
combinate(sourceString);
}
public static void combinate(String sourceString) {
String[] arr = sourceString.split("");
System.out.print("output: ");
for (int i = 0; i < sourceString.length() - 2; i++) {
System.out.print(arr[i] + arr[i + 1] + arr[i + 2] + " ");
}
}
}
// Result
// input: statement
// output: sta tat ate tem eme men ent
答案 1 :(得分:-1)
由于我也是新手,并且不能要求澄清问题,我将假设所需的输出是从第一个数组中取三个字符的增量(因为第二个数组的长度)。要获取数组的这些值,您必须更改此语句:for (int j = i; j < array1.length-array2.length; j++)
to:for (int j = i; j < i + array2.length; j++)
如果您喜欢在嵌套for循环
for (int j = i; j < array1.length-array2.length; j++)
{
System.out.print(array1[j]);
}
System.out.print(" ");
答案 2 :(得分:-1)
你的for循环不正确。它应该是:
for(int i = 0; i <= array1.length - array2.length; i++) {
for(int j = i; j < i + array2.length; j++) {
System.out.print(array1[j]);
}
System.out.print(" ");
}
测试:
act cti tia ian anc nce
说明:
外部for循环从0
循环到array1.length - array2.length
,它们是每种可能组合的起始索引。对于您的示例,它将从0
循环到5
内部for循环从外部for循环的当前索引开始,并递增array2.length
次。我们打印出每个增量的字符,给出组合。
在每个组合(内部循环完成)之后,我们打印出一个空格来分隔组合。
如果您打印出索引,它将如下所示:
i = 0, j = 0, j = 1, j = 2
i = 1, j = 1, j = 2, j = 3
i = 2, j = 2, j = 3, j = 4
i = 3, j = 3, j = 4, j = 5
i = 4, j = 4, j = 5, j = 6
i = 5, j = 5, j = 6, j = 7