# How to create a character array whose each element is just the right length based on its content?

**URL:** <https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166>\
**Category:** Help\
**Created:** [October 26, 2021, 10:44pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166 "2021-10-26T22:44:57Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![CRquantum](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/crquantum/32/730_2.png) [@CRquantum](https://fortran-lang.discourse.group/u/CRquantum)\
**Post date:** [October 26, 2021, 10:44pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/1 "2021-10-26T22:44:57Z")

</div>

Dear all,

A quick question, I want an array, each element is character type.  
But I want the len of each element is just the right size based on its content, instead of a fixed length for all elements. Is there an easy way to achieve this?

See the code below,

```auto
    program main
    character(len=:), allocatable :: string(:)
    character(len=:), allocatable :: string_scalar
    allocate(character(len=20) :: string_scalar)
    allocate(string(5),mold=repeat('0', 20))
    string(1) = '123456789'
    write(6,*) 'string(1) and its size are: ', string(1), len(string(1))
    string_scalar='123456789'
    write(6,*) 'string_scalar and its size are: ', string_scalar, len(string_scalar)
    end program main

```

In this code, string\_scalar has the correct size based on its content ‘123456789’, which is 9.  
However, string(1) has the fixed len=20 which is set when doing allocate.  
Is there a way to let string(1) also have len=9 just like string\_scalar?

Thank you very much in advance!

PS,

The inspiration and technique of string\_scalar is from @everythingfunctional ,

> [@How to read CSV data with fields that contain spaces?](https://fortran-lang.discourse.group/t/how-to-read-csv-data-with-fields-that-contain-spaces/2135/17):
>
> scalars can be allocatable. You can do integer, allocatable :: x allocate(x) x = 42 Of course the above is a little silly, but is perfectly valid. One common case of an allocatable scalar is for polymorphic variables. I.e. class(base\_type), allocatable :: x allocate(child\_type :: x) With deferred length characters you can do character(len=:), allocatable :: string allocate(character(len=42) :: string) string = "Hello, World!" ! This automatically reallocates string to the length of "Hello,…

---

<div class="post-metadata">

**Author:** ![everythingfunctional](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/everythingfunctional/32/176_2.png) [@everythingfunctional](https://fortran-lang.discourse.group/u/everythingfunctional)\
**Post date:** [October 26, 2021, 11:09pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/2 "2021-10-26T23:09:48Z")

</div>

You have to use a separate type, as the length of each character in an array must be the same. Luckily, my implementation of [`iso_varying_string`](https://gitlab.com/everythingfunctional/iso_varying_string) does just that.

---

<div class="post-metadata">

**Author:** ![msz59](https://avatars.discourse-cdn.com/v4/letter/m/3d9bf3/32.png) [@msz59](https://fortran-lang.discourse.group/u/msz59)\
**Post date:** [October 26, 2021, 11:20pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/3 "2021-10-26T23:20:21Z")

</div>

Alternatively, you could use an (possibly allocatable) array of derived type containing an allocatable character component:

```auto
program strings
  type pnt
    character(:), allocatable :: str
  end type pnt
  
  type(pnt), allocatable :: strarr(:)
  
  allocate(strarr(10))
  strarr(1)%str = 'abc'
  strarr(2)%str = '0123456789'
  print *, len(strarr(1)%str), len(strarr(2)%str)
end program strings

```

---

<div class="post-metadata">

**Author:** ![certik](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/certik/32/4_2.png) [@certik](https://fortran-lang.discourse.group/u/certik)\
**Post date:** [October 26, 2021, 11:49pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/4 "2021-10-26T23:49:26Z")

</div>

Can this be done using `stdlib`? Let’s start recommending these basic operations using `stdlib`, and if it is not possible, let’s implement it. I think that will ensure that a regular Fortran compiler + stdlib provides fixes for everything.

---

<div class="post-metadata">

**Author:** ![milancurcic](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/milancurcic/32/2_2.png) [@milancurcic](https://fortran-lang.discourse.group/u/milancurcic)\
**Post date:** [October 27, 2021, 12:11am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/5 "2021-10-27T00:11:00Z")

</div>

Yes, [string\_type](https://stdlib.fortran-lang.org/page/specs/stdlib_string_type.html) in `stdlib_string_type` can do this. Or you can use Brad’s library, or some other, the solutions are all in the same spirit.

---

<div class="post-metadata">

**Author:** ![CRquantum](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/crquantum/32/730_2.png) [@CRquantum](https://fortran-lang.discourse.group/u/CRquantum)\
**Post date:** [October 27, 2021, 12:41am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/6 "2021-10-27T00:41:27Z")

</div>

Thank you very much! @everythingfunctional@msz59 @certik @milancurcic  
I am glad stdlib has this already.

Just a quick follow-up question about the @msz59 solution,  
Since

```auto
  type pnt
    character(:), allocatable :: str
  end type pnt

```

only have one stuff, str.  
Is it possible to directly define type pnt, so that pnt already means character(:), allocatable ,  
so that I can simply use

```auto
strarr(1) = 'abc'
strarr(2) = '0123456789'

```

instead of adding the %str ?  
Like do I need to define the ‘=’ symbol such that

```auto
strarr(1) = 'abc'

```

actually means

```auto
strarr(1)%str = 'abc'

```

Or, is the %str stuff inevitable?

---

<div class="post-metadata">

**Author:** ![milancurcic](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/milancurcic/32/2_2.png) [@milancurcic](https://fortran-lang.discourse.group/u/milancurcic)\
**Post date:** [October 27, 2021, 12:48am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/7 "2021-10-27T00:48:35Z")

</div>

> [@CRquantum](#):
>
> Is it possible to directly define type pnt, so that pnt already means character(:), allocatable ,  
> so that I can simply use
> 
> ```auto
> strarr(1) = 'abc'
> strarr(2) = '0123456789'
> 
> ```
> 
> instead of adding the %str ?

Yes, both the stdlib `string_type` and Brad’s `iso_varying_string` can do this. They provide a custom assignment operator so that you can assign an intrinsic `character` variable to a string instance. See how they’re defined in [stdlib](https://github.com/fortran-lang/stdlib/blob/089f325c63177672ca08d7676e74bcd2fae22ce3/src/stdlib_string_type.fypp#L380) and [`iso_varying_string`](https://gitlab.com/everythingfunctional/iso_varying_string/-/blob/main/src/iso_varying_string.F90#L246).

---

<div class="post-metadata">

**Author:** ![urbanjost](https://avatars.discourse-cdn.com/v4/letter/u/0ea827/32.png) [@urbanjost](https://fortran-lang.discourse.group/u/urbanjost)\
**Post date:** [October 27, 2021, 1:44am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/8 "2021-10-27T01:44:36Z")

</div>

I was thinking that `ASSOCIATE` could be used, albeit in a somewhat cumbersome manner as an alternate way to get a shorter syntax and found I was wrong. I admit to (nearly) never using `ASSOCIATE` except to give short names to values when writing very long formulas; but I was  
surprised the following was not legal if a little inelegant. Wondering if anyone had a short explanation as to why this (having an allocatable on the RHS of `ASSOCIATE`) is not allowed, as it is not apparent to me why it would be:

```fortran
!!
!! W-A-R-N-I-N-G: example of invalid code
!!
type pnt
   character(len=:),allocatable :: str
   !character(len=20) :: str
end type pnt
type(pnt),allocatable :: string_pnt(:)
character(len=:), allocatable :: string_scalar
character(len=*),parameter :: g='(*(g0,1x))'

   allocate(string_pnt(10))
   ASSOCIATE ( string => string_pnt(:)%str )
   
       string(5) = repeat('0',20)
       string(1) = '123456789'
   
       write(*,g) 'string(1) and its size are: ', string(1), len(string(1))
   
       string_scalar = '123456789'
   
       write(*,g) 'string_scalar and its size are: ', string_scalar, len(string_scalar)
   END ASSOCIATE

end program main

```

Note that if I used a fixed-length CHARACTER variable(commented out in the TYPE declaration above) the code compiles and runs just fine, but no longer does what the OP wants.

---

<div class="post-metadata">

**Author:** ![FortranFan](https://avatars.discourse-cdn.com/v4/letter/f/96bed5/32.png) [@FortranFan](https://fortran-lang.discourse.group/u/FortranFan)\
**Post date:** [October 27, 2021, 2:40am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/9 "2021-10-27T02:40:51Z")

</div>

> [@urbanjost](#):
>
> … Wondering if anyone had a short explanation as to why this (having an allocatable on the RHS of `ASSOCIATE` ) is not allowed …

It’s rather difficult to answer “why”, chances are high no definitive source toward the rationale included in the `construct association` section of the standard can be obtained.

The reason is very likely to keep it “safe” (and simpler) when it comes to “pointers” which Fortran has tried since Fortran 90 when it introduced the `POINTER` ↔ `TARGET` as a paired attribute to bring out more of an aliasing facility rather than “raw pointers” into the language. The language does not permit a `TARGET` to be allocated via the `POINTER`.

It’s kinda the same with `selector` and the `associate name` here.

---

<div class="post-metadata">

**Author:** ![FortranFan](https://avatars.discourse-cdn.com/v4/letter/f/96bed5/32.png) [@FortranFan](https://fortran-lang.discourse.group/u/FortranFan)\
**Post date:** [October 27, 2021, 2:54am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/10 "2021-10-27T02:54:40Z")

</div>

> [@certik](#):
>
> Can this be done using `stdlib` ?..

How much longer will it take to realize the use of varying length string types is inherent to scientific and technical computing!!? And for Fortran to provide such a string facility as an **intrinsic type**!

Look at the calendar: no one now should have to invoke an `USE xx` statement preceded by all the steps to package manage `xx` just to consume a string type. Fortranners should simply be able to do

```Fortran
string_t, allocatable :: strings(:)
strings = ["Hello", "World!"]

```

---

<div class="post-metadata">

**Author:** ![certik](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/certik/32/4_2.png) [@certik](https://fortran-lang.discourse.group/u/certik)\
**Post date:** [October 27, 2021, 3:19am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/11 "2021-10-27T03:19:56Z")

</div>

> [@FortranFan](#):
>
> ```auto
> string_t, allocatable :: strings(:)
> strings = ["Hello", "World!"]
> 
> ```

Is the idea to take `string_t` from stdlib (they call it `string_type` — any idea why the longer name? The shorter one seems easier to type and use) and simply include in a compiler itself?

Yes, that is part of our plan to eventually port some things from stdlib into the language itself, after it gets good use. `string_t` can be one such candidate. Alternatively we can see if there is a way to extend the native “character” type to allow this usage.

---

<div class="post-metadata">

**Author:** ![CRquantum](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/crquantum/32/730_2.png) [@CRquantum](https://fortran-lang.discourse.group/u/CRquantum)\
**Post date:** [October 27, 2021, 3:45am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/12 "2021-10-27T03:45:35Z")

</div>

@FortranFan May I ask, what is string\_t ?

---

<div class="post-metadata">

**Author:** ![FortranFan](https://avatars.discourse-cdn.com/v4/letter/f/96bed5/32.png) [@FortranFan](https://fortran-lang.discourse.group/u/FortranFan)\
**Post date:** [October 27, 2021, 11:01am UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/13 "2021-10-27T11:01:25Z")

</div>

@CRquantum , my post included a hypothetical code snippet showing a potential new intrinsic type named `string_t` introduced into the language in a future revision. Such a type is not available currently.

---

<div class="post-metadata">

**Author:** ![msz59](https://avatars.discourse-cdn.com/v4/letter/m/3d9bf3/32.png) [@msz59](https://fortran-lang.discourse.group/u/msz59)\
**Post date:** [October 27, 2021, 12:00pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/14 "2021-10-27T12:00:20Z")

</div>

> [@FortranFan](#):
>
> How much longer will it take to realize the use of varying length string types is inherent to scientific and technical computing!!? And for Fortran to provide such a string facility as an **intrinsic type**!

I couldn’t agree more. Repeating mantras like _"trailing spaces in a text assigned to character variable are not_ significant _any more, indistinguishable from those padded by the processor"_ to the students in the third decade of 21st century is really embarrassing.

But even if not **intrinsic** , does anybody know why the **iso\_varying\_string** , defined as _auxiliary part_ of F95 standard, have not make it to the _primary_ three versions later? Or, at least, to any of commonly used compilers (surely not to GNU gfortran or Intel ifort)?

---

<div class="post-metadata">

**Author:** ![urbanjost](https://avatars.discourse-cdn.com/v4/letter/u/0ea827/32.png) [@urbanjost](https://fortran-lang.discourse.group/u/urbanjost)\
**Post date:** [October 27, 2021, 1:02pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/15 "2021-10-27T13:02:14Z")

</div>

Yes, I see now it seems ASSOCIATE is treated like COMMON or EQUIVALENCE in that it has to point to fixed defined locations, and I (naively, apparently) thought it’s main purpose was to provide a general aliasing capability. Apparently why it is called ASSOCIATE instead of ALIAS! It would be far more useful for my particular wants if it was a general aliasing command. A preprocessing macro (which I prefer to avoid) would be closer to what I wanted than ASSOCIATE ends up being. Thanks!

---

<div class="post-metadata">

**Author:** ![milancurcic](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/milancurcic/32/2_2.png) [@milancurcic](https://fortran-lang.discourse.group/u/milancurcic)\
**Post date:** [October 27, 2021, 3:43pm UTC](https://fortran-lang.discourse.group/t/how-to-create-a-character-array-whose-each-element-is-just-the-right-length-based-on-its-content/2166/16 "2021-10-27T15:43:49Z")

</div>

> [@certik](#):
>
> they call it `string_type` — any idea why the longer name? The shorter one seems easier to type and use

There was a discussion [here](https://github.com/fortran-lang/stdlib/issues/225). I just reviewed it again and it seems that the preference of the community there is fragmented between `<type-name>`, `type-name>_t`, and `<type-name>_type`, all three being acceptable. I believe only the `stdlib_bitsets` module uses the first form, and all others use the third form. So, all three being acceptable it’s down to the implementor, reviewers, and maintainers to decide.

If a stdlib derived type is to be adopted into the standard in the future, it would be renamed anyway to `<type-name>_type` for consistency with existing intrinsic derived types. So, my position as a maintainer is to prefer this form, for readability to newcomers and consistency with the intrinsic types. We can change this, of course, and adopt a different convention, but I haven’t seen a good reason to do that yet.
