简体   繁体   English

打印字符串中的字符(第一个字符;然后是第一个和第二个;然后是第一个,第二个和第三个)

[英]Print characters from a string (first character; then first and second; then first, second, and third)

In java, if I wanted to print out characters from a string in this order: 在Java中,如果我想按以下顺序从字符串中打印出字符:

String str = "abcdefg";
System.out.println("a");
System.out.println("ab");
System.out.println("abc");
System.out.println("abcd");
System.out.println("abcde");
System.out.println("abcdef");
System.out.println("abcdefg");

Which algorithm can I use to do this? 我可以使用哪种算法来做到这一点?

Here is the code you need: 这是您需要的代码:

String str = "abcdefg";
for (int i =1 ;i<str.length();i++){
  System.out.println(str.substring(0,i));
}


For all List elements:

    List<String> list = new ArrayList<String>();
    list.add("abcdefg");
    list.add("hijklm");
    for (String str : list) {
      for (int i =1 ;i<str.length();i++){
        System.out.println(str.substring(0,i));
      }
    }

There are several ways, one would be to use a StringBuilder for example... 有几种方法,一种是例如使用StringBuilder ...

String str = "abcdefg";
StringBuilder sb = new StringBuilder(str.length());
for (char c : str.toCharArray()) {
    sb.append(c);
    System.out.println(sb);
}

This simply takes each character in turn and appends it to the StringBuilder and prints the result...as an example ;) 这只是简单地依次获取每个字符,并将其附加到StringBuilder并打印结果...作为示例;)

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

相关问题 如何打印第一个数组中的单词,第二个数组中的第二个和第三个数组中的第三个的单词组合? - How to print a combination of words one from first array the second from second array and third from third array? 从第二个字符串中删除第一个字符串中存在的字符 - Remove characters from the second string which are present in the first string 打印字符串中的第一大和第二大元素 - To print the first biggest and second biggest elements in a string 如何从某个字符中找出字符串中的第一个,第二个或第三个出现的位置? - How do I find out of a certain character is the first or second or third occurrence in a string? 从第二个字符串中的第一个字符串中查找子字符串? - Find substrings from first string in second String? 将第二个字符串与第一个字符串的第一部分匹配 - match second string with first part of the first string 用于在两个字符之间查找字符串的正则表达式模式-但第二个字符首次出现 - Regex pattern for finding string between two characters - but first occurrence of the second character 用户提供的整数数组的第一,第二和第三大数 - First, Second and Third largest number from user provided integer array 子串 first, second,third, ... , n 匹配 - Substring first, second, third, ... , n match 键入列表的第一个/第二个/第三个参数 - Type the first/second/third parameter of a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM