Find nth occurance of character in Rexx - mainframe

I want to find a nth occurance of character in string in Rexx. Is there any built in function to do this? If no, how can I do this?

Use the POS function n number of times.
E.g to find the 3rd 'a' in a string, use pos("a",string,currentPos) 3 times with the initial start point being 1 and the subsequent start points being the result of the previous pos.
/* REXX */
string = "The quick brown fox jumps over the lazy dog"
srchchar = "e"
count = 2
say "The position of the '"count"' occurrence of '"srchChar"'"||,
" in '"string"' is at position : "
say findChar(srchChar, string, count)
exit
findChar: procedure
/* Find the nth (count) position of the string needle in haystack */
arg needle, haystack, count
currentPos = 0
do count
currentPos = currentPos + 1
currentPos = pos(needle, haystack, currentPos)
end
return currentPos
If you run this, you get :
The position of the '2' occurrence of 'e' in 'The quick brown fox jumps over the lazy dog' is at position :
29
***
This will accept a string as the search argument, not just a single character. If you wanted to enforce the search argument being a single character you could, but I can't see any value in doing so as it adds code and reduces functionality.
E.g.
string = "The quick brown fox jumps over the lazy dog"
srchchar = "the"
count = 2
say "The position of the '"count"' occurrence of '"srchChar"'"||,
" in '"string"' is at position : "
say findChar(srchChar, string, count)
returns:
The position of the '2' occurrence of 'the' in 'The quick brown fox jumps over the lazy dog' is at position :
32
***
EDIT - This is my old (incorrect as I mis-read the quest) answer, that counts the number of times the search character appears in the string.
No built-in function that I know of, but you could write a subroutine to step through the search string character-by-character, comparing the current character with the one you are looking for:
/* REXX */
string = "The quick brown fox jumps over the lazy dog"
srchchar = "q"
say "There is/are "count(srchchar, string)" occurrances of "||,
"'"srchchar"' in '"string"'"
exit
count: procedure
arg needle, haystack
count = 0
do i = 1 to length(haystack)
currentChar = substr(haystack,i,1)
if currentChar = needle then count = count + 1
end
return count
I'm sure there are other ways too.

Here is a sample implementation of a function to return the position of the nth occurrence of a needle within a haystack. The function is called NthPositionOfNeedle.
/*- REXX --------------------------------------------------------------------------
This function returns the position of the nth occurrence of a given character
in a given string. A negative return value indicates a parameter error, or
the fact that the nth occurrence was not found.
Parameters:
Haystack A non-empty string of characters to be search.
Needle A single character to be searched for in the haystack.
Count A whole number indicating the nth occurrence to be found.
Return values:
n where n > 0 indicates the position of the nth occurrence
of the needle within the haystack.
-1 The haystack is an empty string.
-2 The needle is not a single character.
-3 The count is not a whole number > 0.
-4 The needle was not found at all within the haystack.
-5 The nth occurrence was not found, but the needle was
found at least once.
---------------------------------------------------------------------------------*/
NthPositionOfNeedle: procedure
Haystack = arg(1)
Needle = arg(2)
Count = arg(3)
/* The haystack must not be an empty string. Return -1 if it is */
if length( Haystack ) = 0
then return -1
/* The Needle must be a single character. Return -2 if it is not */
if length( Needle ) <> 1
then return -2
/* The count must be a whole number > 0. Return -3 if it is not */
if datatype( Count, "W" ) = 0 | Count < 1
then return -3
/* Does needle exist at least once in the haystack? Return -4 if not */
if pos( Needle, Haystack ) = 0
then return -4
CurrCnt = 0
Start = 1
do while ( CurrCnt < Count & Start <= length( Haystack ) )
NeedlePos = pos( Needle, Haystack, Start )
/* No more occurrences? */
if NeedlePos = 0
then leave
CurrCnt = CurrCnt + 1
Start = NeedlePos + 1
end
/* Return the position of the nth occurrence, if so many exist, else return zero */
if CurrCnt = Count
then return NeedlePos
else return -5
This is the code to test above funtion
/*- REXX --------------------------------------------------------------------------
Code to test the function "NthPositionOfNeedle".
---------------------------------------------------------------------------------*/
say "1st occurrence of 't' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 't', 1 )
/* ....+....1....+....2....+....3....+....4.... */
say "1st occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 1 )
say "2nd occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 2 )
say "3rd occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 3 )
say "6th occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 6 )
say "7th occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 7 )
say "0th occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 0 )
say "2nd occurrence of 'x' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'x', 2 )
say "1st occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( '', 'i', 1 )
say "1st occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', '', 1 )
say "1st occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 0 )
say "1st occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', "a" )
say "1st occurrence of 'i' in 'this is a string with multiple characters i.' is" ,
NthPositionOfNeedle( 'this is a string with multiple characters i.', 'i', 1.1 )
exit

Parse is nice. Usually keeps things short. Here's one way of using it in context of this Q:
/* REXX: PosOfNth: Position of nth character(string) in haystack */
/* tests */
s='Foo Bar Baz'; c='F'; n=1; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
s='Foo Bar Baz'; c='a'; n=1; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
s='Foo Bar Baz'; c='a'; n=2; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
s='Foo Bar Baz'; c='z'; n=1; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
s='Foo Bar Baz'; c='z'; n=2; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
s='Lorem Ipsum'; c='m'; n=1; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
s='Lorem Ipsum'; c='z'; n=1; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
s='Lorem Ipsum'; c='Ips'; n=1; Say n'-th 'c' in 's"="PosOfNth(s,c,n)
/* "visual" test */
Say
s='Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod...'
c='a'; n=2
Say s; Say Left('',PosOfNth(s,c,n)-1,' ')||'^ - 'n'-th 'c' is here'
Exit
/* ===== PROCS ===== */
PosOfNth: Procedure ;
Parse Arg haystack, needle, n
posN = 0
Do n
oHaystack = haystack
Parse Value haystack With head (needle) haystack
If haystack='' & oHaystack<>head||needle Then Do
posN = 0
Leave
End; Else posN = posN + Length(head) + 1
End
posN = posN + (Length(needle)-1) * (n-1)
Return posN
EDIT
As #phunsoft pointed out, there was an issue with multi-char needle (search string). I added line posN = posN + (Length(needle)-1) * (n-1) to adjust for it.

public class character_occurance {
public static void main(String[] args) {
String str1 = "bcdabghbghjbjkib";
int count = 0;
for (int i = 0; i <str1.length(); i++) {
if (str1.charAt(i) == 'j') {
count=count+1;
}
}System.out.println(count);
}
}

Related

Python3 String Manipulation Using Replacement

I want to create a list of vowels from a string that contains letters and still have the consonants in that string. I have something that worked for a particular string, with one occurrence in that string but when I have multiple occurrences, it does not work.
PRINCELY worked well,
EMEKA did not work.
I need help!
alphabets = {"A":1,"B":2,"C":3, "D":4,"E":5,"F":6,"G":7,"H":8,"I":9,"J":1,"K":2,"L":3,"M":4,"N":5,"O":6,"P":7,"Q":8,"R":9,"S":1,
"T":2,"U":3,"V":4,"W":5, "X":6,"Y":7,"Z":8}
def digit_sum(num):
return sum( [ int(char) for char in str(num) ] )
def numerology(word):
total = 0
for letter in word:
total += alphabets[letter]
total = digit_sum(total)
return total
fan = 'PRINCELY'
def vowels(fan):
vowels=[]
if 'I' in fan:
vowels.append(9)
fan1=fan[:fan.index('I')]+fan[fan.index('I')+1:]
consonant = fan1
if 'E' in fan:
vowels.append(5)
fan2=fan1[:fan1.index('E')]+fan1[fan1.index('E')+1:]
consonant = fan2
if 'A' in fan:
vowels.append(1)
fan3=fan2[:fan2.index('A')]+fan2[fan2.index('A')+1:]
consonant = fan3
if 'O' in fan:
vowels.append(6)
fan4=fan3[:fan3.index('O')]+fan3[fan3.index('O')+1:]
consonant = fan4
if 'U' in fan:
vowels.append(3)
fan5=fan4[:fan4.index('U')]+fan4[fan4.index('U')+1:]
consonant = fan5
print(vowels)
print(consonant)
print(digit_sum(sum(vowels)))
cons = numerology(consonant)
print(cons)
vowels(fan)
#outputs
#[9, 5]
#PRNCLY
#5
#7
The easiest way is to use str.translate with an appropriate translation table. First we'll make a function that takes a character and returns the appropriate number as a string. We'll use that to build a translation table. Then we just use that translation table on the string
def get_number(char):
return str(ord(char.lower())-96) # lowercase ascii letters start at 97
vowels = (vowel for letter in 'aeiou' for vowel in (letter, letter.upper()))
table = str.maketrans({vowel: get_number(vowel) for vowel in vowels})
print('PRINCELYPRINCELY'.translate(table))
# PR9NC5LYPR9NC5LY
To sort the string into vowels and consonants, and then turn the vowels into numbers you could do
s = 'PRINCELYPRINCELY'
vowels = [ord(char.lower())-96 for char in s if char.lower() in 'aeiou']
# [9, 5, 9, 5]
consonants = s.translate(str.maketrans('','','aeiouAEIOU'))
# 'PRNCLYPRNCLY'

What does "for letter in greeting" do in the given code?

greeting = 'Hello!'
count = 0
for letter in greeting:
count += 1
if count % 2 == 0:
print(letter)
print(letter)
print('done')
Strings in Python are sequences of individual characters, so what for letter in greeting does is to iterate through each character in the string greeting, and assign each character to the variable letter in each iteration.
Your answer will be :
!
!
done
Detailed Explanation :-
Your string is greeting='Hello!'
You have initialized Count to 0
In line, " for letter in greeting: " --> letter is not a property of for loop but simply a variable that will hold each alphabet of string in incrementing iterations. You can also use --> for i in greeting: --> then 'i' will contain each alphabet of string stored in variable 'greeting'.
Then Count+=1 , will execute for all letters in string "Hello!" i.e H,e,l,l,o,! --> Count = 6.
Then it will check that if Count is divisible by 2 or "is an even number" then it will display "letter" i.e. '!' because after complete execution of above 'for loop' the last value in variable letter is '!'. Since, if statement results in true, it will print '!' followed by '!' and finally 'done'.

Skipping spaces in Groovy

I'm trying to write a conditional statement where I can skip a specific space then start reading all the characters after it.
I was thinking to use substring but that wouldn't help because substring will only work if I know the exact number of characters I want to skip but in this case, I want to skip a specific space to read characters afterward.
For example:
String text = "ABC DEF W YZ" //number of characters before the spaces are unknown
String test = "A"
if ( test == "A") {
return text (/*escape the first two space and return anything after that*/)
}
You can split your string on " " with tokenize, remove the first N elements from the returned array (where N is the number of spaces you want to ignore) and join what's left with " ".
Supposing your N is 2:
String text = "ABC DEF W YZ" //number of characters before the spaces are unknown
String test = "A"
if ( test == "A") {
return text.tokenize(" ").drop(2).join(" ")
}

In Groovy Language How to replace a character in a string based on the value and position in the string

I am looking to amend the values of a string IF certain positions within a string are certain values for example I have a postcode L65 OBH and I need to do the following:
(1)
If the 1st value in the first section of the string (split by white space) = L it needs to be changed to T. This would then give:
T65 OBH
(2)
Then if the 2nd value in the first section of the string (split by white space) = 6 it needs to be changed to 7. This would then give:
T75 OBH
(3)
Then if the 1st value in the second section of the string (split by white space) = O it needs to be changed to 2. This would then give:
T75 2BH
(4)
Then if the 3rd value in the second section of the string (split by white space) = H it needs to be changed to P. This would then give:
T75 2BP
I'm assuming that I need to use replaceall and a number of IF statements but I am struggling to work this out, particularly how to split the 2 different parts of the postcode out treat them as separate enteties....can anyone help please
I'd write a helper method for the replacement rules:
def postcode = 'L65 0BH'
def (first, second) = postcode.split(/\s+/)
def replaceIf(String token, int position, String match, String replacement) {
(0..<token.length()).collect { index ->
if(index == position && token[index] == match) {
replacement
}
else {
token[index]
}
}.join()
}
first = replaceIf(first, 0, 'L', 'T')
first = replaceIf(first, 1, '6', '7')
second = replaceIf(second, 0, '0', '2')
second = replaceIf(second, 2, 'H', 'P')
assert "$first $second" == 'T75 2BP'
def strVal= "L65 OBH"
strVal.replaceFirst(/^L/, "T")
def strVal1= "L65 OBH"
strVal1.replaceFirst(/^6/, "7")
and so on using the same replaceFirst() method

Python Join String to Produce Combinations For All Words in String

If my string is this: 'this is a string', how can I produce all possible combinations by joining each word with its neighboring word?
What this output would look like:
this is a string
thisis a string
thisisa string
thisisastring
thisis astring
this isa string
this isastring
this is astring
What I have tried:
s = 'this is a string'.split()
for i, l in enumerate(s):
''.join(s[0:i])+' '.join(s[i:])
This produces:
'this is a string'
'thisis a string'
'thisisa string'
'thisisastring'
I realize I need to change the s[0:i] part because it's statically anchored at 0 but I don't know how to move to the next word is while still including this in the output.
A simpler (and 3x faster than the accepted answer) way to use itertools product:
s = 'this is a string'
s2 = s.replace('%', '%%').replace(' ', '%s')
for i in itertools.product((' ', ''), repeat=s.count(' ')):
print(s2 % i)
You can also use itertools.product():
import itertools
s = 'this is a string'
words = s.split()
for t in itertools.product(range(len('01')), repeat=len(words)-1):
print(''.join([words[i]+t[i]*' ' for i in range(len(t))])+words[-1])
Well, it took me a little longer than I expected... this is actually tricker than I thought :)
The main idea:
The number of spaces when you split the string is the length or the split array - 1. In our example there are 3 spaces:
'this is a string'
^ ^ ^
We'll take a binary representation of all the options to have/not have either one of the spaces, so in our case it'll be:
000
001
011
100
101
...
and for each option we'll generate the sentence respectively, where 111 represents all 3 spaces: 'this is a string' and 000 represents no-space at all: 'thisisastring'
def binaries(n):
res = []
for x in range(n ** 2 - 1):
tmp = bin(x)
res.append(tmp.replace('0b', '').zfill(n))
return res
def generate(arr, bins):
res = []
for bin in bins:
tmp = arr[0]
i = 1
for digit in list(bin):
if digit == '1':
tmp = tmp + " " + arr[i]
else:
tmp = tmp + arr[i]
i += 1
res.append(tmp)
return res
def combinations(string):
s = string.split(' ')
bins = binaries(len(s) - 1)
res = generate(s, bins)
return res
print combinations('this is a string')
# ['thisisastring', 'thisisa string', 'thisis astring', 'thisis a string', 'this isastring', 'this isa string', 'this is astring', 'this is a string']
UPDATE:
I now see that Amadan thought of the same idea - kudos for being quicker than me to think about! Great minds think alike ;)
The easiest is to do it recursively.
Terminating condition: Schrödinger join of a single element list is that word.
Recurring condition: say that L is the Schrödinger join of all the words but the first. Then the Schrödinger join of the list consists of all elements from L with the first word directly prepended, and all elements from L with the first word prepended with an intervening space.
(Assuming you are missing thisis astring by accident. If it is deliberately, I am sure I have no idea what the question is :P )
Another, non-recursive way you can do it is to enumerate all numbers from 0 to 2^(number of words - 1) - 1, then use the binary representation of each number as a selector whether or not a space needs to be present. So, for example, the abovementioned thisis astring corresponds to 0b010, for "nospace, space, nospace".

Resources