how to remove empty spaces between '=' and values in fortran - fortran

I read data from a file and parse them to store in some variables. Data are written as below in the file,
INT_VALUE = 17 # Valid Integer
INT_VALUE1 23
INT_VALUE2 = 00012
INT_VALUE3 -2
INT_VALUE4 -33
In some places there are spaces and '=' in some other places. While reading I get my stream%val with '='and my value comes as ' = 17' of which I need to remove = and the spaces between '=' symbol and the first number and store as a valid number.
In some other cases there might be spaces between the numbers which should be an error.
Invalid values will be any non integer/real values with special characters. For example,
INT_VALUE13 34=5434
INT_VALUE14 -23 45-33
INT_VALUE15 = 23-45*665Rtre
INT_VALUE16 -23.4
INT_VALUE17 1.4E9r23
INT_VALUE18 -5.D-3.3
INT_VALUE19 233 ddf
INT_VALUE20 -87 dfsdf
INT_VALUE21 = rtmr,t23./
How do I remove the spaces in fortran?
My function is,
character(60) function sweep_blanks(in_str)
character(*), intent(in) :: in_str
character(60) :: out_str
character :: ch
integer :: j
out_str = " "
do j=1, len_trim(in_str)
ch = in_str(j:j)
if (ch .ne. " ") then
out_str = trim(out_str) // ch
endif
sweep_blanks = out_str
end do
end function sweep_blanks
This removes all blanks irrespective of in the middle or at the end or at the beginning which doesn't help.

You can do this using the two functions index and adjustl.
index finds the location of a substring within a string;
adjustl makes leading blanks trailing blanks.
integer idx
idx = INDEX(instring, '=')+1
outstring = ADJUSTL(instring(idx:))
So, given the input string
instring = ' = 17'
the index result will be 2, giving idx value 3. instring(3:) has the value ' 17' from which adjustl' returns '17 '
Given the input string
instring = ' -33'
without the '=' the index result will be 0.

Related

Need to separate out Letters from numbers in a string, via vb.net

I would like my code to find anywhere in the string that there is a number next to a letter and insert a space between the two.
I have several addresses that have no spaces and I need to insert spaces by separating out the numbers from the letters. For example:
123MainSt.Box123
Should be 123 Main St. Box 123
or
123Parkway134
should be: 123 Parkway 134
Here is where I started with my code but it was combing both numbers in the beginning....
Dim Digits() As String = Regex.Split(Address, "[^0-9]+")
'MsgBox(Digits.Count)
If Digits.Length > 2 Then
' For Each item As String In Digits
Dim Letters As String = Regex.Replace(Address, "(?:[0-9]+\.?[0-9]*|\.[0-9]+)", "")
rCell.Value = Digits(0) & Letters & Digits(1)
End If
If Digits.Length < 3 Then
If Address.Contains("th") Then
Else
Dim Part1 As String = Regex.Replace(Address, "[^0-9]+", "")
Dim Part2 As String = Regex.Replace(Address, "(?:[0-9]+\.?[0-9]*|\.[0-9]+)", "")
'MsgBox(Part1 & " " & Part2)
rCell.Value = Part1 & " " & Part2
End If
End If
I would like my code to find anywhere in the string that there is a number next to a letter and insert a space between the two.
The regex you may use is
Regex.Replace(input, "(?<=\d)(?=\p{L})|(?<=\p{L})(?=\d)", " ")
The first alternative - (?<=\d)(?=\p{L}) - matches the location between a digit and a letter, and the second alternative - (?<=\p{L})(?=\d) - matches a location between a letter and a digit.
Note that (?<=\p{L}) is a positive lookbehind that requires a letter before the current position and (?=\d) is a positive lookahead that requires a digit after the current position. These are lookarounds that do not consume text, thus, you replace empty spaces with (= insert) a space.
Here's a quick function:
Private Function AddSpaces(ByVal input As String) As String
If input.Length < 2 Then Return input
Dim ReturnValue As String = String.Empty
Dim CurrentChar, NextChar As String
For x As Integer = 1 To input.Length
CurrentChar = Mid(input, x, 1)
NextChar = Mid(input, x + 1, 1)
ReturnValue &= CurrentChar
If (IsNumeric(CurrentChar) AndAlso (Not IsNumeric(NextChar))) OrElse
((Not IsNumeric(CurrentChar)) AndAlso IsNumeric(NextChar)) Then
ReturnValue &= " "
End If
Next
Return ReturnValue
End Function

VB.net read a text file and populate a combobox with specific extracted words

I have a problem which is giving me a headache. I really thought someone would have asked this already, but days of reading and testing has been fruitless.
I have a text file which starts:
"Determining profile based on KDBG search...
Suggested Profile(s) : WinXPSP2x86, WinXPSP3x86 (Instantiated with WinXPSP2x86)"
(The blank line between the two is not an error and neither are the spaces before 'Suggested')
I need to read the line starting 'Suggested...' only and extract every unique word starting 'Win' and populate a combobox with them. (i.e. 'WinXPSP2x86' and 'WinXPSP3x86')
I know i need to use the 'StreamReader' class and probably get a Regex going on, but, as a beginner, connecting it all together is beyond my knowledge at the moment.
Can anyone help? It would be much appreciated.
Imports System.IO
Public Class Form1
Private Sub Form1_Load( sender As Object, e As EventArgs) Handles MyBase.Load
' BASIC is case sensitive and e is parameter so we will start
' new variables with the letter f.
' Read all lines of file into string array F.
Dim F As String() = File.ReadAllLines("H:\Projects\35021241\Input.txt")
' F() is a 0 based array. Assign 3 line of file to G.
Dim G As String = F(2)
' On line 3 of file find starting position of the word 'win' and assign to H.
' TODO: If it is not found H will be -1 and we should quit.
Dim H As Integer = G.IndexOf("Win")
' Assign everything beginning at 'win' on line 3 to variable I.
Dim I As String = G.Substring(H)
' The value placed in delimiter will separate remaining values in I.
' Place C after ending quote to represent a single character as opposed to a string.
Dim Delimiter As Char = ","C
' J array will contain values left in line 3.
Dim J As String() = I.Split(Delimiter)
' Loop through J array removing anything in parenthesis.
For L = J.GetLowerBound(0) to J.GetUpperBound(0)
' Get location of open parenthesis.
Dim ParenBegin As Integer = J(L).IndexOf("(")
' If no open parenthesis found continue.
If ParenBegin <> -1 then
' Open parenthesis found. Find closing parenthesis location
' starting relative to first parenthesis.
Dim Temp As String = J(L).Substring(ParenBegin+1)
' Get location of ending parenthesis.
Dim ParenEnd As Integer = Temp.IndexOf(")")
' TODO: Likely an exception will be thrown if no ending parenthesis.
J(L) = J(L).Substring(0,ParenBegin) & J(L).Substring(ParenBegin + ParenEnd +2)
' Change to include text up to open parenthesis and after closing parenthesis.
End If
Next L
' UnwantedChars contains a list of characters that will be removed.
Dim UnwantedChars As String = ",()"""
' Check each value in J() for presence of each unwanted character.
For K As Integer = 0 to (UnwantedChars.Length-1)
For L = J.GetLowerBound(0) To J.GetUpperBound(0)
' Declare M here so scope will be valid at loop statement.
Dim M As Integer = 0
Do
' Assign M the location of the unwanted character or -1 if not found.
M= J(L).IndexOf(UnwantedChars.Substring(K,1))
' Was this unwanted character found in this value?
If M<>-1 Then
' Yes - where was it found in the value?
Select Case M
Case 0 ' Beginning of value
J(L) = J(L).Substring(1)
Case J(L).Length ' End of value.
J(L) = J(L).Substring(0,(M-1))
Case Else ' Somewhere in-between.
J(L) = J(L).Substring(0,M) & J(L).Substring(M+1)
End Select
Else
' No the unwanted character was not found in this value.
End If
Loop Until M=-1 ' Go see if there are more of this unwanted character in the value.
Next L ' Next value.
Next K ' Next unwanted character.
' Loop through all the values and trip spaces from beginning and end of each.
For L As Integer = J.GetLowerBound(0) To J.GetUpperBound(0)
J(L) = J(L).Trim
Next L
' Assign the J array to the combobox.
ComboBox1.DataSource = J
End Sub
End Class
As some have already suggested:
Use System.IO.File.ReadAllLines, if the file is not too big
Iterate through the array of lines
For each line, use the Split method to split on space
Check the first three characters of each word
This works but does of course need some error checking etc:
Dim lines() As String = System.IO.File.ReadAllLines("c:\temp\example.txt")
Dim lineWords() As String
For Each line As String In lines
lineWords = line.Split(New Char() {" "}, System.StringSplitOptions.RemoveEmptyEntries)
For Each word As String In lineWords
If word.Length > 3 Then
If word.Substring(0, 3).ToUpper = "WIN" Then
cmbWords.Items.Add(word)
End If
End If
Next
Next

Printing out values from a function

Ok so the issue with my program is that for some reason when I run it the variables at the bottom come out as "None" instead of the count of the amount of ATG's in the original strings of HumanDNA, MouseDNA, and UnknownDNA. I couldn't add the part where i define these DNA's because of their length and was difficult for me to add it. How can I change it so instead it outputs the amount of times the substring is found in the original string as a variable that is outside the function and can output it in the format I have at the bottom.
def countCodon(string, substring):
i = string.find(substring)
def compareDNA(string1, string2):
string1 = raw_input("Enter string 1: ")
string2 = raw_input("Enter string 2: ")
Hamming = 0
for ch1, ch2 in zip(string1, string2):
if ch1 != ch2:
Hamming += 1
l = len(string1)
similarity_score = ((l - Hamming)/(l))
print similarity_score
HD = countCodon(humanDNA, "ATG")
MD = countCodon(mouseDNA, "ATG")
UD = countCodon(unknownDNA, "ATG")
print "Mouse: ", HD
print "Human: ", MD
print "Unknown: ", UD
MU = compareDNA(mouseDNA, unknownDNA)
HU = compareDNA(humanDNA, unknownDNA)
if MU != HU and MU > HU:
print "mouse"
elif MU != HU and MU < HU:
print "human"
elif MU == HU:
print "identity cannot be determined"
EDIT: Added the messed up part of the second function running into a similar problem.
countCodon() has no return value so HD = None
Moreover from https://docs.python.org/2/library/string.html
string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
So countCodon() is giving you the index where the string "ATG" first appears, not the number of times it is present.

VBA code for extracting 3 specific number patterns

I am working in excel and need VBA code to extract 3 specific number patterns. In column A I have several rows of strings which include alphabetical characters, numbers, and punctuation. I need to remove all characters except those found in a 13-digit number (containing only numbers), a ten-digit number (containing only numbers), or a 9-digit number immediately followed by an "x" character. These are isbn numbers.
The remaining characters should be separated by one, and only one, space. So, for the following string found in A1: "There are several books here, including 0192145789 and 9781245687456. Also, the book with isbn 045789541x is included. This book is one of 100000000 copies."
The output should be: 0192145789 9781245687456 045789541x
Note that the number 100000000 should not be included in the output because it does not match any of the three patterns mentioned above.
I'm not opposed to a excel formula solution as opposed to VBA, but I assumed that VBA would be cleaner. Thanks in advance.
Here's a VBA function that will do specifically what you've specified
Function ExtractNumbers(inputStr As String) As String
Dim outputStr As String
Dim bNumDetected As Boolean
Dim numCount As Integer
Dim numStart As Integer
numCount = 0
bNumDetected = False
For i = 1 To Len(inputStr)
If IsNumeric(Mid(inputStr, i, 1)) Then
numCount = numCount + 1
If Not bNumDetected Then
bNumDetected = True
bNumStart = i
End If
If (numCount = 9 And Mid(inputStr, i + 1, 1) = "x") Or _
numCount = 13 And Not IsNumeric(Mid(inputStr, i + 1, 1)) Or _
numCount = 10 And Not IsNumeric(Mid(inputStr, i + 1, 1)) Then
If numCount = 9 Then
outputStr = outputStr & Mid(inputStr, bNumStart, numCount) & "x "
Else
outputStr = outputStr & Mid(inputStr, bNumStart, numCount) & " "
End If
End If
Else
numCount = 0
bNumDetected = False
End If
Next i
ExtractNumbers = Trim(outputStr)
End Function
It's nothing fancy, just uses string functions to goes through your string one character at a time looking for sections of 9 digit numbers ending with x, 10 digit numbers and 13 digit numbers and extracts them into a new string.
It's a UDF so you can use it as a formula in your workbook

Fortran: Integer to String Example

I'm trying to write a simple Fortran code, for practicing. It is supposed to multiply numbers in a range. Each time, the resulting product is converted into a string because I want to see if it consists of the same digits.
I tested the way I transform an integer into a string and typed the components of the string, and everything was going correctly. Then, I need to compare the components of the string, for which I use string(number:number). But I couldn't get the code to do this correctly.
Here's the code and the output:
program test
implicit none
character(10) myString
character(1) a,b,c,d,e,f
integer::i,j,k
do i=900,901,1
j=900
k=i*j
write(*,*)'k =', k
write(myString,'(i10)') k
write(*,*)'myString = ', myString
a=myString(1:1)
b=myString(2:2)
c=myString(3:3)
d=myString(4:4)
e=myString(5:5)
f=myString(6:6)
print*,a,b,c,d,e,f
if (d==f) then
print*,'hobla'
else
print*,'fobla'
end if
end do
stop
end program test
So I defined characters: a,b,c,d,e,f to contain the components of the string. And used myString(i:i) to locate each component and store it in one of the characters a,b,c,d,e,f.
But it seems only the first two are working correctly, the rest is not being stored!
Output:
k = 810000
myString = 810000
81
fobla
k = 810900
myString = 810900
81
fobla
Notice 81. This was supposed to give 810000 the first time, and print "hobla". And give 810900 the second time and print "fobla". But this didn't happen!
Can anybody show me how to let myString accept the zeros as characters?
This statement
write(myString,'(i10)') k
writes the value of k into a 10-character field. Since k has only 6 significant digits the first 4 characters in myString are filled with blanks. Then you assign the first 6 characters of myString (that is 4 blanks and the digits 8 and 1) to the variables a,b,c,d,e,f and print them out -- 4 blanks and 2 digits.
Try printing out the other characters in positions 7..10 of myString and you should see your 'missing' digits.
Okay, so I figured out the problem. Consider the following modifications to your code:
program test
implicit none
character(10) myString
character(1) a,b,c,d,e,f
integer::i,j,k
do i=900,901,1
j=900
k=i*j
write(*,*)'k =', k
write(myString,'(i10)') k
write(*,*)'myString = ', myString
a=myString(1:1)
b=myString(2:2)
c=myString(3:3)
d=myString(4:4)
e=myString(5:5)
f=myString(6:6)
write(*,*) a
write(*,*) b
write(*,*) c
write(*,*) d
write(*,*) e
write(*,*) f
if (d==f) then
print*,'hobla'
else
print*,'fobla'
end if
end do
stop
end program test
The resulting output is:
k = 810000
myString = 810000
8
1
fobla
k = 810900
myString = 810900
8
1
fobla
This happens because the I format right-justifies numbers when printed. So there is a bunch of leading white-spaces because your number is only 6 digits while your string you are writing into is 10. So you get 4 leading spaces.
If you change your format string so you have:
write(myString,'(i10.10)') k
then instead of padding with spaces it will pad with 0's. That way you can always have digits to compare if you would rather.