How to Find Specific Value to Specific String Location in Different Strings

How to find specific VALUE to specific STRING location in different strings

Grab a copy of DelimitedSplit8K then you can do this:

DECLARE @string1 VARCHAR(1000) = ',x,x,y,x,x,O,x,y',
@string2 VARCHAR(1000) = '0~1~b~~z~XY~1~7';

DECLARE @search VARCHAR(1000) = 'O'; -- best as a variable/parameter

SELECT *
FROM dbo.delimitedSplit8K(@string2,'~') AS s
WHERE s.itemNumber =
(
SELECT TOP (1) s2.itemNumber -- TOP (1) until we know about dupicates
FROM dbo.delimitedSplit8K(@string1,',') AS s2
WHERE s2.item = @search
)-1;

Returns:

ItemNumber           Item
-------------------- -------
6 XY

Check if list contains element that contains a string and get that element

You should be able to use Linq here:

var matchingvalues = myList
.Where(stringToCheck => stringToCheck.Contains(myString));

If you simply wish to return the first matching item:

var match = myList
.FirstOrDefault(stringToCheck => stringToCheck.Contains(myString));

if(match != null)
//Do stuff

How to find all occurrences of a substring?

There is no simple built-in string function that does what you're looking for, but you could use the more powerful regular expressions:

import re
[m.start() for m in re.finditer('test', 'test test test test')]
#[0, 5, 10, 15]

If you want to find overlapping matches, lookahead will do that:

[m.start() for m in re.finditer('(?=tt)', 'ttt')]
#[0, 1]

If you want a reverse find-all without overlaps, you can combine positive and negative lookahead into an expression like this:

search = 'tt'
[m.start() for m in re.finditer('(?=%s)(?!.{1,%d}%s)' % (search, len(search)-1, search), 'ttt')]
#[1]

re.finditer returns a generator, so you could change the [] in the above to () to get a generator instead of a list which will be more efficient if you're only iterating through the results once.

How do I get the position of a string inside a list in Python?

This code of yours is messed up a bit


space = ' ' # This is fine but redundant
for space in sentence: # Shouldn't reuse variable names. Should be <for char in sentence. But I wouldn't use that either since we don't need the char it self but the index
if space in sentence: #Should be <if char == space> Your just returns a True if there's a single space anywhere in the string. Assuming it's using the correct variable named space. Honestly I don't know what this code will do since I didn't run it :P
space_position = sentence[space]
print(space_position)

Here's what I would do, which could be done better since I'm a beginner too.

sentence = input('Please type a sentence: ')

for i in range(len(sentence)):
if sentence[i] == " ":
print(i)

#>>>Please type a sentence: A sentence and spaces
#>>>1
#>>>10
#>>>14

How to get a string after a specific substring?

The easiest way is probably just to split on your target word

my_string="hello python world , i'm a beginner"
print(my_string.split("world",1)[1])

split takes the word (or character) to split on and optionally a limit to the number of splits.

In this example, split on "world" and limit it to only one split.

Finding all indexes of a specified character within a string

A simple loop works well:

var str = "scissors";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === "s") indices.push(i);
}

Now, you indicate that you want 1,4,5,8. This will give you 0, 3, 4, 7 since indexes are zero-based. So you could add one:

if (str[i] === "s") indices.push(i+1);

and now it will give you your expected result.

A fiddle can be see here.

I don't think looping through the whole is terribly efficient

As far as performance goes, I don't think this is something that you need to be gravely worried about until you start hitting problems.

Here is a jsPerf test comparing various answers. In Safari 5.1, the IndexOf performs the best. In Chrome 19, the for loop is the fastest.

Sample Image

How to find indices of all occurrences of one string in another in JavaScript?

var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}

UPDATE

I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.

function getIndicesOf(searchStr, str, caseSensitive) {    var searchStrLen = searchStr.length;    if (searchStrLen == 0) {        return [];    }    var startIndex = 0, index, indices = [];    if (!caseSensitive) {        str = str.toLowerCase();        searchStr = searchStr.toLowerCase();    }    while ((index = str.indexOf(searchStr, startIndex)) > -1) {        indices.push(index);        startIndex = index + searchStrLen;    }    return indices;}
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");
document.getElementById("output").innerHTML = indices + "";
<div id="output"></div>

How to check a string for specific characters?

Assuming your string is s:

'$' in s        # found
'$' not in s # not found

# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found

And so on for other characters.

... or

pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found')
else
print('Not found')

... or

chars = set('0123456789$,')
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')

[Edit: added the '$' in s answers]



Related Topics



Leave a reply



Submit