删除字符串中的空格 [英] Removing whitespace in string

查看:158
本文介绍了删除字符串中的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  program main 
character(len = 15):: abc = te tex t
print *,trim(abc)
end program main

哪些产出:

  te st tex t 

我除去了所有要删除的空白,但不是。我怎样才能从字符串中删除所有的空白字符?

解决方案

修剪将仅在边缘而不是中间移除空格(这是几乎所有语言/库的常见行为) 。如果要删除字符串中的所有空格,则必须创建自己的函数来完成此操作,并遍历字符串。



例如:

 程序测试

隐式无

!变量
字符(len = 200):: string

!测试体
string ='Hello World 7 9'
print *,string
调用StripSpaces(string)
print *,string


包含
$ b子例程StripSpaces(字符串)
字符(len = *):: string
integer :: stringLen
integer :: last,actual

stringLen = len(string)
last = 1
actual = 1

while(实际< stringLen)
if(string(last :last)=='')然后
actual = actual + 1
string(last:last)= string(actual:actual)
string(actual:actual)=''
else
last = last + 1
if(actual< last)&
actual = last
endif
end do

结束子程序

结束程序测试

这是在intel编译器上测试过的,而不是在gfortran上测试的,但我认为它会起作用。


I have the following code:

  program main
     character (len=15) :: abc = "te st tex  t"
     print *, trim(abc)      
  end program main

Which outputs:

 te st tex  t

I excepted all the whitespace to be removed but it wasn't. How can I remove all the whitespace from the string?

解决方案

Trim will remove spaces only at the edges, not in the middle (this is common behaviour on almost all languages/libraries). If you want to remove all spaces in the string, you will have to create your own function to do this, iterating through the string.

Ex.:

program Test

implicit none

    ! Variables
    character(len=200) :: string

    ! Body of Test
    string = 'Hello World              7    9'
    print *, string
    call StripSpaces (string)
    print *, string


contains

    subroutine StripSpaces(string)
    character(len=*) :: string
    integer :: stringLen 
    integer :: last, actual

    stringLen = len (string)
    last = 1
    actual = 1

    do while (actual < stringLen)
        if (string(last:last) == ' ') then
            actual = actual + 1
            string(last:last) = string(actual:actual)
            string(actual:actual) = ' '
        else
            last = last + 1
            if (actual < last) &
                actual = last
        endif
    end do

    end subroutine

end program Test

This was tested on intel compiler, not on gfortran, but I think it will work.

这篇关于删除字符串中的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆