If I have a string, for example "Tiger," what could I write that would return T + i + g + e + r? It would be nice if I could put each letter inside of an array.
I need this because I'm writing a program that analyzes an inputted string and determines how many times repeated letters occur.
Try String.split() method with empty delimeter:
var str:String = "Tiger";
var letters:Array = str.split('');
//result-> ["T","i","g","e","r"]
Related
I using split method to split the String.
String date = "2020-10-07";
date.split("-");
print("split " + date[0]);
I expect will get 2020, but why it return 2 ?
The reason you are getting 2 is because it is the first position (0) of the string variable date.
When you split a string, it will return a list/array.
String date = "2020-10-07";
final dateList = date.split("-");
print("split " + dateList[0]);
//expected "split 2020"
It is 2 because there no change has been done to the variable date( the same without the split), but with split you can access the list like this below
String date = "2020-10-07";
var first = date.split("-").first;//returns the first element of the list
print("split " + first);
(Any String).split(Pattern) returns List<String>.
Since no operation was done to change the variable (it anyhow can't store List<String>).
You are left with:
Temporarily store the split as #Morgan Hunt and #Henok Suggested
print("split " + date.split("-").first); (I guess you are going to return the first split)
Also data[0] -> is an operation on a string hence you are getting 0th position -> 2
I need to take only the letters and numbers at the beginning of a string, but some numbers are decimals. The strings are not all formatted the same. Here are a few examples of some of the data and what I would need returned:
HB61 .M16 1973 I need HB61 returned
HB97.52 .R6163 1982 I need HB97.52 returned
HB98.V38 1994 I need HB98 returned
HB 119.G74 A3 2007 I need HB119 returned
I'm very new to coding so I'm hoping there's some simple solution that I just don't know?
I was going to just split it at the first dot and then get rid of the spaces, but this wouldn't allow me to keep the decimals such as HB97.52 which I need. I currently have code written just to test one string at a time. The code is as follows:
data = input("Data: ")
components = data.split(".")
str(components)
print(components[0].replace(" ", ""))
This works as expected except for the strings with decimals. for HB97.52 .R6163 1982 I would like HB97.52 returned but it only returns HB97.
The following regular expression extracts the letters at the beginning of a string, followed by optional spaces, followed by a [possibly floating point] number:
s = ['HB61 .M16 1973', 'HB97.52 .R6163 1982',
'HB98.V38 1994', 'HB 119.G74 A3 2007']
import re
pattern = r"^[a-z]+\s*\d+(?:\.\d+)?"
[re.findall(pattern, part, flags=re.I)[0] for part in s]
#['HB61', 'HB97.52', 'HB98', 'HB 119']
If you do not want the spaces in the output, this slightly different pattern extracts the letter part and the number part separately, and then they are joined:
pattern = r"(^[a-z]+)\s*(\d+(?:\.\d+)?)"
list(map("".join, [re.findall(pattern, part, flags=re.I)[0] for part in s]))
#['HB61', 'HB97.52', 'HB98', 'HB119']
For something like HB61.45.78.R5000 what do you want? If you want HB61.45.78 then use this first snippet:
data = data.replace(' ', '')
data = data.split('.')
wanted = data[0]
for i in range(1,len(data)):
if data[i][0].isalpha():
break
else:
wanted += '.' + data[i]
Otherwise, if you want only HB61.45 then use
data = data.replace(' ', '')
data = data.split('.')
wanted = data[0]
if not data[1][0].isalpha():
wanted += '.' + data[1]
My question is more or less similar to:
Is there a way to substring a string in Python?
but it's more specifically oriented.
How can I get a par of a string which is located between two known words in the initial string.
Example:
mySrting = "this is the initial string"
Substring = "initial"
knowing that "the" and "string" are the two known words in the string that can be used to get the substring.
Thank you!
You can start with simple string manipulation here. str.index is your best friend there, as it will tell you the position of a substring within a string; and you can also start searching somewhere later in the string:
>>> myString = "this is the initial string"
>>> myString.index('the')
8
>>> myString.index('string', 8)
20
Looking at the slice [8:20], we already get close to what we want:
>>> myString[8:20]
'the initial '
Of course, since we found the beginning position of 'the', we need to account for its length. And finally, we might want to strip whitespace:
>>> myString[8 + 3:20]
' initial '
>>> myString[8 + 3:20].strip()
'initial'
Combined, you would do this:
startIndex = myString.index('the')
substring = myString[startIndex + 3 : myString.index('string', startIndex)].strip()
If you want to look for matches multiple times, then you just need to repeat doing this while looking only at the rest of the string. Since str.index will only ever find the first match, you can use this to scan the string very efficiently:
searchString = 'this is the initial string but I added the relevant string pair a few more times into the search string.'
startWord = 'the'
endWord = 'string'
results = []
index = 0
while True:
try:
startIndex = searchString.index(startWord, index)
endIndex = searchString.index(endWord, startIndex)
results.append(searchString[startIndex + len(startWord):endIndex].strip())
# move the index to the end
index = endIndex + len(endWord)
except ValueError:
# str.index raises a ValueError if there is no match; in that
# case we know that we’re done looking at the string, so we can
# break out of the loop
break
print(results)
# ['initial', 'relevant', 'search']
You can also try something like this:
mystring = "this is the initial string"
mystring = mystring.strip().split(" ")
for i in range(1,len(mystring)-1):
if(mystring[i-1] == "the" and mystring[i+1] == "string"):
print(mystring[i])
I suggest using a combination of list, split and join methods.
This should help if you are looking for more than 1 word in the substring.
Turn the string into array:
words = list(string.split())
Get the index of your opening and closing markers then return the substring:
open = words.index('the')
close = words.index('string')
substring = ''.join(words[open+1:close])
You may want to improve a bit with the checking for the validity before proceeding.
If your problem gets more complex, i.e multiple occurrences of the pair values, I suggest using regular expression.
import re
substring = ''.join(re.findall(r'the (.+?) string', string))
The re should store substrings separately if you view them in list.
I am using the spaces between the description to rule out the spaces between words, you can modify to your needs as well.
I have a string which is this:
a = 'Sound_impro_Act'
I want to divide this into multiple strings which are the words that are seperated by '_' and assign these to different variables.
The end result will be like this:
b = 'Sound'
c = 'impro'
d = 'act'
Thanks.
You may also use regexp which is faster than strsplit
a = 'Sound_impro_Act';
parts = regexp(a,'_','split');
[b,c,d] = deal(parts{:});
The last line comes from #Divakar's answer. Lots of thanks!
Use strsplit and then deal to put them into different variables -
split_strings = strsplit(a,'_')
[b,c,d] = deal(split_strings{:})
strsplit function can do it for you:
An example:
a = 'Sound_impro_Act';
b= strsplit(a, '_');
now you can access all splited values using b(1), b(2), b(3)
I'm trying to merge cell-array of strings delimiting each by new line to one string in Matlab.
Following method merges the strings, but the final string contains \n instead of new lines:
function str = toString(self)
% some not important logic that creates cell array called strings
% ...
str = '';
for i = 1 : 9
str = strcat(str, strings(i), '\n');
end
end
It returns: ' 111\n 111\n 111\n333666444555\n333666444555\n333666444555\n 222\n 222\n 222\n'
When I add str = sprintf(str); before the end of the method, it returns Invalid format error. However when I write to Matlab command window sprintf(' 111\n 111\n 111\n333666444555\n333666444555\n333666444555\n 222\n 222\n 222\n'); it returns formatted string without any errors.
Anyone knows what could be a problem? Why it works in command window but doesn't in .m file?
sprintf will loop over the elements or your cell array:
sprintf('%s\n', strings{:})
The problem with your loop is '\n' is a 2 element char array, but what you want is sprintf('\n')