Jump to content

Limit String entry length

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
Xdawn90

Xdawn90

    Learning Programmer

  • Members
  • PipPipPip
  • 55 posts
Hi,

is there a way for me to limit the length of the String entered to one ?

Thanks.

#2
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
Do you want to limit it for other programmer or user?

i think there's no simple way - think of all the methods that could fail because of this limit.
You can write a class that grants access to the String.

class LimitedString{
     private String str;
     private int limit;
     public LimitedString(int limit){
          this.limit = limit;
     }
     public boolean set(String str){
          if(str.length() <= limit){
                this.str = str;
                return true;
          }
          else return false;
     }
     public String toString(){
          return str;
     }
}

Edited by Sinipull, 09 July 2009 - 12:54 AM.


#3
Xdawn90

Xdawn90

    Learning Programmer

  • Members
  • PipPipPip
  • 55 posts
Thanks for the suggestion. I will try it out.

I have another question:

How to allow the user to enter a string with spaces in between by using scanner ?

Help is much appreciated. Thanks.

#4
BlaineSch

BlaineSch

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,448 posts
You can use substring
string.substring(start, end);


#5
Xdawn90

Xdawn90

    Learning Programmer

  • Members
  • PipPipPip
  • 55 posts
Can you show me the way to do it ?

Thanks.

#6
BlaineSch

BlaineSch

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,448 posts
I did, string is the string name, start and end are both ints based on where you want to start or end, the beginning of the string is 0 and the last would be string.length()