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不改變行。
添加回答
舉報