2 回答
TA贡献1900条经验 获得超5个赞
在没有提供代码时编写 - 早些时候它被标记为C。
以问题陈述中描述的方式打印字符串是简单的递归。这是执行此操作的C等效代码(因为此问题也已在Java 中标记):
#include<stdio.h>
int i=1;
void fun(char c[])
{
int j=0;
while((j<i)&&(c[j]))
{
printf("%c",c[j++]);
}
while((c[j]=='\0')&&(j<i))
{
printf("*");
++j;
}
++i;
if(c[j])
{
printf(" ");
fun(c+j);
}
}
int main(void)
{
char c[]="computer";
fun(c);
return 0;
}
输出:
c om put er**
如果要替换\0检查,则可以使用字符串的长度作为检查,因为我不知道 Java 中是否存在空终止。
TA贡献1871条经验 获得超8个赞
Java 版本,因为注释不适用于代码:
String str = "computer";
int k = 0;
for (int i=0; k<str.length(); i++) { // note: condition using k
for (int j=0; j<i; j++) {
if (k < str.length()) {
System.out.print(str.charAt(k++));
} else {
System.out.print("*"); // after the end of the array
}
}
System.out.println();
}
未经测试,只是一个想法
注意:没有必要使用,split因为我们想要字符串的每个字符 - 我们可以使用charAt(或toCharArray)。使用print而不是println不改变行。
添加回答
举报