为了账号安全,请及时绑定邮箱和手机立即绑定

打印字符串模式的Java程序

打印字符串模式的Java程序

LEATH 2021-10-06 09:45:56
如果输入字符串是“ADMINISTRATIONS”,则模式应该是这样的 A DM INI STRA TIONS最后一行应该完全填满如果输入字符串是“COMPUTER”,则模式应该是这样的 COM PUT ER**不完整的最后一行应该用 * 填充我有图案,但无法打印星星。    int k=0;    String str = "computer";    String[] s=str.split("\\B");    for(int i=0; i<s.length;i++){        for(int j=0; j<i;j++){            if(k<s.length){        System.out.println(s[k]);        k++;            }    }        System.out.println();帮我解决这个问题。
查看完整描述

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 中是否存在空终止。


查看完整回答
反对 回复 2021-10-06
?
ITMISS

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不改变行。


查看完整回答
反对 回复 2021-10-06
  • 2 回答
  • 0 关注
  • 203 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信