Zeklaus
Zeklaus

Reputation: 1

Looking to restrict the length of a string in Java

I'd like to count the amount of characters within a string, and cut off any excess characters of the string. I thought of just using a while loop and a char, but I need to pass in a string. I also tried to use the remainder function, but I"m pretty sure it wouldn't work.

So, essentially, a counter for a string and then to limit that string to x amount of characters.

If I were to set the string to a single character, say

String x = "*";

Then implemented a counter in a for loop...

for(int i = 0; i < 6; i++){
???
}

Would that work? I feel like it wouldn't, and that it would just be more effective for me to declare

char x = 'a';

...

I'm trying to make this as vague as possible so that I can take ideas and implement them so it's not like I'm stealing anybody's code for homework, I just need a little help.

Upvotes: 0

Views: 12016

Answers (2)

Raheel138
Raheel138

Reputation: 147

"I was searching around on the web for a manual code to count the amount of characters within a string, and then to a further extent cut off any excess characters of the string."

Count amount of characters within a string:

int length = stringName.length();

Cutting off extra characters of the string

int maxAmount; //wherever you want to stop
if(length > maxAmount)
{
    stringName = stringName.substring(0,stopPoint);
}

Upvotes: 0

Alex Salauyou
Alex Salauyou

Reputation: 14338

String myString = "myString";
int maxLength = 3;
if (myString.length() > maxLength)
     myString = myString.substring(0, maxLength);

Result will be "myS"

Upvotes: 2

Related Questions