0

I need to take a string and assign each character to a new string variable for a Text To Speech engine to read out each character separately, mainly to control the speed at which it's read out by adding pauses in between each character.

The string contains a number which can vary in length from 6 digits to 16 digits, and I've put the below code together for 6 digits but would like something neater to handle any different character count.

I've done a fair bit of research but can't seem to find a solution, plus I'm new to Groovy / programming.

OrigNum= "12 34 56"
Num = OrigNum.replace(' ','')
sNum = Num.split("(?!^)")
sDigit1 = sNum[0]
sDigit2 = sNum[1]
sDigit3 = sNum[2]
sDigit4 = sNum[3]
sDigit5 = sNum[4]
sDigit6 = sNum[5]

Edit: The reason for needing a new variable for each character is the app that I'm using doesn't let the TTS engine run any code. I have to specifically declare a variable beforehand for it to be read out

Sample TTS input: "The number is [var:sDigit1] [pause] [var:sDigit2] [pause]..."

I've tried using [var:sNum[0]] [var:sNum[1]] to read from the map instead but it is not recognised.

2
  • why do you need a new (?) variable per char? Commented Jun 18, 2020 at 9:09
  • Original post updated, this is required for TTS to work as it doesn't run code Commented Jun 19, 2020 at 0:20

2 Answers 2

0

Read this about dynamically creating variable names.

You could use a map in your stuation, which is cleaner and more groovy:

Map digits = [:]
OrigNum.replaceAll("\\s","").eachWithIndex { digit, index ->
    digits[index] = digit
}

println digits[0]       //first element == 1
println digits[-1]      //last element == 6
println digits.size()   // 6
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks but a Map won't work as each digit needs its own variable, I've updated my original post for clarity around this requirement.
0

Not 100% sure what you need, but to convert your input String to output you could use:

String origNum = "12 34 56"
String out = 'The number is ' + origNum.replaceAll( /\s/, '' ).collect{ "[var:$it]" }.join( ' [pause] ' )

gives:

The number is [var:1] [pause] [var:2] [pause] [var:3] [pause] [var:4] [pause] [var:5] [pause] [var:6]

1 Comment

Thanks, at first I wasn't sure the [pause] being part of the string would be understood by TTS but it did!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.