• Post Reply Bookmark Topic Watch Topic
  • New Topic

substring problem  RSS feed

 
chaitanya karthikk
Ranch Hand
Posts: 806
Java MySQL Database Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everybody, I am Chaitanya, I am having a problem and forgot which function to use.

I am having a String variable, I have to take out the first 15 characters out from it, I have written this code

str1.subString(0,14);

Suppose if the string length is less than 15 I will get an error, I don't know how to fix this problem.

Can anyone please help me? Thank you all in advance.
 
Sudipta Laha
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
check String API

Use str.length() to find the size of String. If less than 15, do substring upto str.length() else your code.
 
chaitanya karthikk
Ranch Hand
Posts: 806
Java MySQL Database Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey sorry guys, I fixed the problem.

System.out.print("Krishna Chaitanya".substring(0,Math.min("Krishna Chaitanya".length(), 15)));
 
Daniel Sagayaraj
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why dont you make it simple



System.out.print("Krishna Chaitanya".substring(0,15));
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yamuna Daniel wrote:why dont you make it simple



System.out.print("Krishna Chaitanya".substring(0,15));


Read the original post and you'll see why that's not suitable.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because that will throw an exception if the String has less than 15 characters.
 
chaitanya karthikk
Ranch Hand
Posts: 806
Java MySQL Database Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Yamuna Daniel

If we simply use "Krishna Chaitanya".substring(0,15) we might get error some times. Suppose if the String length is less than 15, then your program runs into errors
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!