Limit String Length

Limit String Length

You can use something similar to the below:

if (strlen($str) > 10)
$str = substr($str, 0, 7) . '...';

C#: Limit the length of a string?

Strings in C# are immutable and in some sense it means that they are fixed-size.

However you cannot constrain a string variable to only accept n-character strings. If you define a string variable, it can be assigned any string. If truncating strings (or throwing errors) is essential part of your business logic, consider doing so in your specific class' property setters (that's what Jon suggested, and it's the most natural way of creating constraints on values in .NET).

If you just want to make sure isn't too long (e.g. when passing it as a parameter to some legacy code), truncate it manually:

const int MaxLength = 5;

var name = "Christopher";
if (name.Length > MaxLength)
name = name.Substring(0, MaxLength); // name = "Chris"

What is the maximum possible length of a .NET string?

The theoretical limit may be 2,147,483,647, but the practical limit is nowhere near that. Since no single object in a .NET program may be over 2GB and the string type uses UTF-16 (2 bytes for each character), the best you could do is 1,073,741,823, but you're not likely to ever be able to allocate that on a 32-bit machine.

This is one of those situations where "If you have to ask, you're probably doing something wrong."

C - Limit the string length

You must specify the length to print or terminate the string. Otherwise, you will invoke undefined behavior. Try this, in which the latter method is implemented.

#include <stdio.h>
#define MAXCHAR 8

int main(void)
{
char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
int i;
char c;

printf("Insert password: MAX 8 CHARS!\n\n");
for(i = 0; i <= MAXCHAR; i++){
c = getchar();

if(i == MAXCHAR){
break;
}
else{
password[i] = c;
}
}
password[MAXCHAR] = '\0'; /* terminate the string */

printf("%s\n", password);
}

Some people say that the if(i == MAXCHAR){ break; } part doesn't look good, so here is another code example:

#include <stdio.h>
#define MAXCHAR 8

int main(void)
{
char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
int i;

printf("Insert password: MAX 8 CHARS!\n\n");
/* read exactly 8 characters. To improve, breaking on seeing newline or EOF may be good */
for(i = 0; i < MAXCHAR; i++){
password[i] = getchar();
}
password[MAXCHAR] = '\0'; /* terminate the string */
getchar(); /* to match number of call of getchar() to the original: maybe for consuming newline character after 8-digit password */

printf("%s\n", password);
}

Java with String length limit

Can anyone confirm if this is indeed a limitation of Java?

Yes. There is an implementation limit of 65535 on the length of a string literal1. It is not stated in the JLS, but it is implied by the structure of the class file; see JVM Spec 4.4.7 and note that the string length field is 'u2' ... which means a 16 bit unsigned integer.

Note that a String object can have up to 2^31 - 1 characters. The 2^16 -1 limit is actually for string-valued constant expressions; e.g. string literals or concatenations of literals that are embedded in the source code of a Java program.


If you want to a String that represents the first million digits of Pi, then it would be better to read the characters from a file in the filesystem, or a resource on the classpath.


1 - This limit is actually on the number of bytes in the (modified) UTF-8 representation of the String. If the string consists of characters in the range 0x01 to 0x7f, then each byte represents a single character. Otherwise, a character can require up to 6 bytes.

Limit string length of all cells in a dataframe?

In the OP's code, the str_trunc by default uses ellipsis = "...". If we change it to blank (""), it should give the same output as above. The output of lapply is a list, so we can assign it back to the data.frame or wrap with data.frame to convert the list to data.frame

library(stringr)
g1[] <- lapply(g1, str_trunc, 5, ellipsis = "")
g1
# gene value
#1 aaaaa 1fdfd
#2 aaaaa 2fdfd
#3 aaaaa fdfdf
#4 a 5ffff
#5 bbbbb 0

Or we can use base R by converting the data.frame to matrix and use substr from base R without a loop

g1[] <- substr(as.matrix(g1), 1, 5)
g1
# gene value
#1 aaaaa 1fdfd
#2 aaaaa 2fdfd
#3 aaaaa fdfdf
#4 a 5ffff
#5 bbbbb 0

Or using tidyverse

library(dplyr) #1.0.0
library(stringr)
g1 %>%
mutate(across(everything(), str_sub, 1, 5))
# gene value
#1 aaaaa 1fdfd
#2 aaaaa 2fdfd
#3 aaaaa fdfdf
#4 a 5ffff
#5 bbbbb 0

If we have a dplyr version < 1.0.0, an option is mutate_all

g1 %>%
mutate_all(str_sub, 1, 5)

Limiting the number of characters in a string, and chopping off the rest

Use this to cut off the non needed characters:

String.substring(0, maxLength); 

Example:

String aString ="123456789";
String cutString = aString.substring(0, 4);
// Output is: "1234"

To ensure you are not getting an IndexOutOfBoundsException when the input string is less than the expected length do the following instead:

int maxLength = (inputString.length() < MAX_CHAR)?inputString.length():MAX_CHAR;
inputString = inputString.substring(0, maxLength);

If you want your integers and doubles to have a certain length then I suggest you use NumberFormat to format your numbers instead of cutting off their string representation.

How many characters can a Java String have?

You should be able to get a String of length

  1. Integer.MAX_VALUE always 2,147,483,647 (231 - 1)

    (Defined by the Java specification, the maximum size of an array, which the String class uses for internal storage)

    OR

  2. Half your maximum heap size (since each character is two bytes) whichever is smaller.



Related Topics



Leave a reply



Submit