简体   繁体   中英

Printing only the first 5 characters of a string in one line

Im trying to print just the first 5 characters of a given string in one line. My problem is the whole string is not being printed. Part of the end is being cut off.

  int l = 0;
      int m = 5;
      for(int i = 0; i < (string.length()/5) ; i++)
      {
            System.out.println(string.substring(j,k));
            l = m;
            m = m + 5;

      }

Given string = "Hello world, my name is something which you want to" The result would be something like:

Hello
 worl
d, my

However, the last parts of the string is not being printed.

However, the last parts of the string is not being printed.

Yes, that's right - because of your loop condition. You're iterating (string.length()/5) times - which rounds down. So if the string has 12 characters, you'll only iterate twice... leaving out the last two letters.

I would suggest solving this slightly differently - get rid of the l and m variables (which I assume you meant to use in your substring call - you never declare j or k ) and use the variable in the for loop instead. You need to make sure that you don't try to use substring past the end of the string though - Math.min is handy for that:

for (int sectionStart = 0; sectionStart < string.length(); sectionStart += 5) {
    int sectionEnd = Math.min(string.length(), sectionStart + 5);
    System.out.println(string.substring(sectionStart, sectionEnd);
}

From your question what I understood is, you need output like

Hello

 worl

d, my 

name 

is so

String str="Hello world, my name is something which you want to";
    for(int i=0;i<str.length();i++)
    {
        if(i%5==0 && i!=0)
        {
            System.out.println("");
        }
        System.out.print(str.charAt(i));


    }

Adding one more Approach

String str="Hello world, my name is something which you want to";
    for(int i=0,j=0;i<str.length();)
    {
        if(j<str.length() && (str.length()-j)>5)
        {j=i+5;}
        else
        {j=str.length();}
        System.out.println(str.substring(i,j));
        i+=5;
    }

Output:

Hello

 worl

d, my

 name

 is s

ometh

ing w

hich 

you w

ant t

o

Your variables are all over the place. You have i , j , k , l , m ; some of which are not defined in the code you present.

But you should only have one: beginning of substring, say i . End of substring is always 5 more: (i + 5) . Then increment it by 5 each loopthrough.

Simple Recursive method

void test(String t){

        if(t.length() > 4){
        String o = t.substring(0,5);
        System.out.println(o);
        String x = t.substring(5,t.length());
        test(x);
        }
        else{
            System.out.println(t);
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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