Index and length must refer to a location within the string.? - substring

My input strings are
inputData = "99998UNKNOWN"
inputData = "01000AMEBACIDE/TRICHOM/ANTIBAC 1"
inputData = "34343AMEBACIDE/TRICHOM/ANTIBACSADWA1"
ID = inputData.Substring(0,5);
Name = inputData.Substring(5,30);
Level = inputData.Substring(35,1);
I am getting the below error,
Index and length must refer to a location within the string.
I can understand , the error is due to the length that specified in substring for "Name" is not matching with first input.
Is there any way to handle this issue with any input length?

One approach is to add a "sentinel" suffix to the end of the string before taking substrings. Now you can add it to the data string before taking substrings from it. As long as the suffix has sufficient length, you would never get an index/length exception:
var padded = inputData.PadRight(32);
ID = padded.Substring(0, 5).Trim();
Name = padded.Substring(5, 30).Trim();
Level = padded.Substring(30, 1).Trim();
However, now your code should check if ID, Name, or Level is empty.

Related

How to get upper str this case

I want to get upper"T"..
how to get upper string!
str = "Test Version"
print(str.upper())
print(str[3])
It's not clear what you are asking.
But from context I am guessing you would like to make the second non-capitalised "t" in the string uppercase. I'm also going to assume you are using python 3 given your use of upper().
If you just want to get the "t" (and not change the string itself):
upper_T = str[3].upper()
If you want to create a string from the original you may be running into the fact that strings in python are immutable. You therefore must create a new string.
One way do this:
str2 = list(str)
str2[3] = str[3].upper()
str2 = ''.join(str2)

Swift 4: Trim last character of string based on character

I'm trying to remove the last numbers of an IP address string in Swift so I can loop through IP addresses. For instance if my variable = 192.168.1.123, I would like to trim the string to equal 192.169.1.
I'm not sure how to do this since some IP addresses will end in 1, 2 or 3 digits. I couldn't figure out how to trim back to a certain character.
I have a solution (In your case only). You can try it
let str = "192.168.1.123"
var arr = str.components(separatedBy: ".")
arr.removeLast()
let newstr = arr.joined(separator: ".") + "."
You can find the range of the last .:
let ip = "192.168.1.123"
let lastdot = ip.range(of: ".", options: .backwards)!
let base = ip[...lastdot.lowerBound]
This code assumes there is at least one . in the string. If not it will crash. That is easily fixed with proper use of if let.
base will be a Substring so depending on what you do next, you may need to wrap that as:
let base = String(ip[...lastdot.lowerBound])
Whether explicitly converting to String depends on whether subsequent methods require String or StringProtocol. Converting to String copies over the storage again, which is costly and unnecessary for many operations, but may be required in some cases.

How do I find a partial string in a Mongo database using a superset string?

If my database contains entries with the following string values for the "key" field:
"a,b,c"
"a,b,z"
"a,b,c,d,e,f,z"
"d,e,f,g"
"d,e,f,g,z"
"h,i"
And I have a string like this:
"a,b,c,d,e,f,g,h"
How do I find the entries where the value of the key field matches the start of my string? E.g. I want to find the entry where the value of the key field is "a,b,c".
How do I find the entries where the value of the key field matches any part of my string? E.g. I want to find the entries where the value of the key field is "a,b,c" and "d,e,f,g".
To give some context in case anyone thinks this is a pointless task, I want to do stack matching. I will have entries in a database that identify bugs by the first N frames of the stack and then I want to identify bug(s) by the stack obtained from a core dump.
The answer is to use the $where operator. An example in Python, where search_string is the string we want to find matches with, is:
search_string = 'a,b,c,d,e,f,g,h'
js_check = 'function () { var search_string=\'' + search_string + '\'; return search_string.indexOf(this.key) >= 0; }'
matches = my_collection.find({'$where': js_check})

Need to format fieldname of structure in MATLAB

I have field name which contains (.) for matlab structure
When I create structure, it throws invalid field name error
e.g
fieldName = 'Freq.01'
Structure
s.(fieldName) = 25;
As pointed out in Yuans's comment, fieldnames must not contain '.'. This may be the case because the Value of a field can be another field. Maybe you want to replace the '.' with '_' and then use your new valid fieldname:
fieldname = 'Freq.01';
fieldname = strrep(fieldname, '.', '_');
s.(fieldname) = 25
s.('hello').('world') = 17
You can use matlab.lang.makeValidName to convert an invalid name such as 'Freq.01' into something that is a valid name. (This is only available in relatively recent versions of MATLAB).
In older versions of MATLAB, you can use genvarname.

Regexp to find a matching condition in a string

Hi need help in using regexp for condition matching.
ex.my file has the following content
{hello.program='function'`;
bye.program='script'; }
I am trying to use regexp to match the string that has .program='function' in them:
pattern = '[.program]+\=(function)'
also tried pattern='[^\n]*(.hello=function)[^\n]*';
pattern_match = regexp(myfilename,pattern , 'match')
but this returns me pattern_match={} while i expect the result to be hello.program='function'`;
If 'function' comes with string-markers, you need to include these in the match. Also, you need to escape the dot (otherwise, it's considered "any character"). [.program]+ looks for one or several letters contained in the square brackets - but you can just look for program instead. Also, you don't need to escape the =-sign (which is probably what messed up the match).
cst = {'hello.program=''function''';'bye.program=''script'''; };
pat = 'hello\.program=''function''';
out = regexp(cst,pat,'match');
out{1}{1} %# first string from list, first match
hello.program='function'
EDIT
In response to the comment
my file contains
m2 = S.Parameter;
m2.Value = matlabstandard;
m2.Volatility = 'Tunable';
m2.Configurability = 'None';
m2.ReferenceInterfaceFile ='';
m2.DataType = 'auto';
my objective is to find all the lines that match, .DataType='auto'
Here's how you find the matching lines with regexp
%# read the file with textscan into a variable txt
fid = fopen('myFile.m');
txt = textscan(fid,'%s');
fclose(fid);
txt = txt{1};
%# find the match. Allow spaces and equal signs between DataType and 'auto'
match = regexp(txt,'\.DataType[ =]+''auto''','match')
%# match is not empty only if a match was found. Identify the non-empty match
matchedLine = find(~cellfun(#isempty,match));
Try this as it matches .program='function' exactly:
(\.)program='function'
I think this did not work:
'[.program]+\=(function)'
because of how the []'s work. Here is a link explaining why I say that: http://www.regular-expressions.info/charclass.html