简体   繁体   English

打印字符串模式的Java程序

[英]Java program to print a string pattern

if the input string is "ADMINISTRATIONS" the pattern should be like this A DM INI STRA TIONS如果输入字符串是“ADMINISTRATIONS”,则模式应该是这样的 A DM INI STRA TIONS

The last row should be completely filled最后一行应该完全填满

if the input string is "COMPUTER" the pattern should be like this C OM PUT ER**如果输入字符串是“COMPUTER”,则模式应该是这样的 COM PUT ER**

the incomplete last row should be filled with *不完整的最后一行应该用 * 填充

i have got the pattern but couldnt print the stars.我有图案,但无法打印星星。

    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();

Help me to solve this.帮我解决这个问题。

Written when no code was provided - earlier it was tagged under C .在没有提供代码时编写 - 早些时候它被标记为C

It is simple recursive to print string in the way described in the problem statement.以问题陈述中描述的方式打印字符串是简单的递归。 Here is a C equivalent code to do this (as this question has been tagged in Java as well):这是执行此操作的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;
  }

OUTPUT:输出:

 c om put er**

If you want to replace the \\0 check then you can use the length of string as a check as I am not aware if null termination is there in Java.如果要替换\\0检查,则可以使用字符串的长度作为检查,因为我不知道 Java 中是否存在空终止。

Java version, since comments are not appropriate for code: 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();
}

not tested, just an idea未经测试,只是一个想法

Notes: there is no need to use split since we want each character of the string - we can use charAt (or toCharArray ).注意:没有必要使用split因为我们想要字符串的每个字符 - 我们可以使用charAt (或toCharArray )。 Using print instead of println to not change lines.使用print而不是println不改变行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM