How to split a string into multiple strings if spaces are detected (GM:Studio) - string

I made a console program, but the problem is that it doesn't allow parameters to be inserted. So I'm wondering how would I split a single string into multiple strings to achieve what I need. E.g.: text="msg Hello" would be split into textA="msg" and textB="Hello"
This is the main console code so far (just to show the idea):
if (keyboard_check_pressed(vk_enter)) {
text_console_c = asset_get_index("scr_local_"+string(keyboard_string));
if (text_console_c > -1) {
text_console+= "> "+keyboard_string+"#";
script_execute(text_console_c);
text_console_c = -1;
}
else if (keyboard_string = "") {
text_console+= ">#";
}
else {
text_console+= "> Unknown command: "+keyboard_string+"#";
};
keyboard_string = "";
}

I cant recommend spliting string with iteration by char, because when u try split very very very long string, then time to split is very long and can freeze thread for a short/long time. Game maker is single threaded for now.
This code is much faster.
string_split
var str = argument[0] //string to split
var delimiter = argument[1] // delimiter
var letDelimiter = false // append delimiter to each part
if(argument_count == 3)
letDelimiter = argument[2]
var list = ds_list_create()
var d_at = string_pos(delimiter, str)
while(d_at > 0) {
var part = string_delete(str, d_at , string_length(str))
if(letDelimiter)
part = part + delimiter
str = string_delete(str, 1, d_at)
d_at = string_pos(delimiter, str)
ds_list_add(list, part)
if(d_at == 0 && str != "")//last string without delimiter, need to add too
ds_list_add(list, str)
}
return list;
Dont forget ds_list_destroy after you iterate all strings
for example:
var splited = string_split("first part|second part", '|')
for(splited) {
//do something with each string
}
ds_list_destroy(splited)

Something like this may help, haven't tested it out but if you can follow what is going on its a good place to start.
Text = "msg Hello"
counter = 0
stringIndex = 0
for (i = 0; i < string_length(text); i++)
{
if string_char_at(text,i) == " "
{
counter++
stringIndex = 0
} else {
string_insert(string_char_at(text,i),allStrings(counter),stringIndex)
stringIndex++
}
}
allStrings should be an array containing each of the separate strings. Whenever a " " is seen the next index of allStrings starts having it's characters filled in. stringIndex is used to add the progressive characters.

Related

Simple Longest Word problem.. but for some reason code not working and need help debugging

This was the question: Have the function LongestWord(sen) take the sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume sen will not be empty.
Examples
Input: "fun&!! time"
Output: time
Input: "I love dogs"
Output: love
This is my code: I am pretty sure I'm doing everything right... but I'm not getting the right answer.
function LongestWord(sen){
var sen = sen.toLowerCase()
var string = "abcdefghijklmnopqrstuvwxyz"
var alphabet_array = string.split("")
//loop thru the sen.
var currentWord = ""
var maxWord = ""
var currentCount = 0
var maxCount = 0
for (let i = 0; i < sen.length; i++){
var currentChar = sen[i]
if (currentChar !== " "){
//we are in the middle of a word
if (alphabet_array.includes(currentChar)){
currentWord += currentChar
currentCount++
}
// console.log(currentWord)
}
// if not in the middle, we at the end
else{
if (currentCount > maxCount){
maxCount = currentCount
maxWord = currentWord
}
console.log(maxWord)
//HAVE TO RESET YOUR CONDITIONS
currentWord = ""
currentCount = 0
}
} //end of for loop
return maxWord
}
You need to store the max value in a list and then compare those values outside of the loop.
The script is currently only comparing the first word it sees and not waiting for it to compares max length of all the other words.
Hope it helps :)

How to convert this string 20346017621 in to 20-34601762-1

How we can set up a function on node
After first two number and last number, we want to add - hyphen
able to get a string
like this:xxzzzzzzzzx
and convert in to this:xx-zzzzzzzz-x
example of what we need
function tranformer (xxzzzzzzzzx){
NOT SURE HOW TO SOLVE THIS
return xx-zzzzzzzz-x
}
Thanks we really will appreciate this!
Not idea how to mange this task.
function tranformer(st) {
let newStr = ""
for (let i = 0; i < st.length; i++) {
if (i === 2 || i === st.length - 1) {
newStr += "-"
}
newStr += st[i]
}
return newStr
}
Using Slice
let first = st.slice(0, 2)
let middle = st.slice(2, -1)
let last = st.slice(-1)
newStr = first + "-" + middle + "-" + last
console.log(newStr)
First I would decompose the string into an array, and then use splice command to insert a - char at the specified position:
let str = "xxzzzzzzzzx";
str = str.split('');
str.splice(2, 0, '-'); // insert - at pos 2
str.splice(str.length - 1, 0, '-'); // insert - at pos -1
console.log(str.join('')) //-> xx-zzzzzzzz-x

Reverse every other word in string, keep punctuation Swift

So I got stuck on a coding challenge that I almost knew the answer too. And I think I have to use the subString call in Swift 4 to get it 100%. I want to reverse every OTHER word in a string, but ignore or keep the punctuation in its original place( index ).
var sample = "lets start. And not worry about proper sentences."
func reverseString(inputString: String) -> String {
let oldSentence = sample.components(separatedBy: " ")
var newSentence = ""
for index in 0...oldSentence.count - 1 {
let word = oldSentence[index]
if newSentence != "" {
newSentence += " "
}
if index % 2 == 1 {
let reverseWord = String(word.reversed())
newSentence += reverseWord
} else {
newSentence += word
}
}
return newSentence
}
reverseString(inputString: sample)
And this would be the expected output.
"lets trats. And ton worry tuoba proper secnetnes."
Notice the punctuation is not reversed.
You shouldn't use components(separatedBy: ) to split a string in words. See this article for the reason. Use enumerateSubstrings and pass in the appropriate option:
func reverseString(inputString: String) -> String {
var index = 1
var newSentence = inputString
inputString.enumerateSubstrings(in: inputString.startIndex..., options: .byWords) { substr, range, _, stop in
guard let substr = substr else { return }
if index % 2 == 0 {
newSentence = newSentence.replacingCharacters(in: range, with: String(substr.reversed()))
}
index += 1
}
return newSentence
}
print(reverseString(inputString: "lets start. And not worry about proper sentences."))
// lets trats. And ton worry tuoba proper secnetnes.
print(reverseString(inputString: "I think, therefore I'm"))
// I kniht, therefore m'I

Selecting a tuple index using a variable in Swift

That is what i am trying to do:
var i = 0
var string = "abcdef"
for value in string
{
value.[Put value of variable i here] = "a"
i++
}
How can i insert the value of i in the code?
Easiest is probably just convert it to an NSMutableString:
let string = "abcdef".mutableCopy() as NSMutableString
println( "\(string)")
for var i = 0; i < string.length; ++i {
string.replaceCharactersInRange(NSMakeRange(i, 1), withString: "a")
}
println( "\(string)")
Yes, it's a bit ugly but it works.
A much cleaner way is to use Swifts map function:
var string = "abcdef"
let result = map(string) { (c) -> Character in
"a"
}
println("\(result)") // aaaaaa
You should just be able to use the following but this doesn't compile:
map(string) { "a" }
In you comments you mention you want to split up the string on a space, you can just use this for that:
let stringWithSpace = "abcdef 012345"
let splitString = stringWithSpace.componentsSeparatedByString(" ")
println("\(splitString[0])") // abcdef
println("\(splitString[1])") // 012345

Two digit numbers [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I need a program that takes a two digit number such as "22" and returns "Twenty Two". I have the following started for the main method but have nothing for the string method
static string TwoDigit(int n)
{
}
static void Main(string[] args)
{
for (int i = 0; i <= 19; i++)
Console.WriteLine("{0}: {1}", i, TwoDigit(i));
for (int i = 20; i <= 110; i += 7)
Console.WriteLine("{0}: {1}", i, TwoDigit(i));
}
I don't know of an existing program but it would be easy to write the function.
I would convert the int to a string then do a switch statement on each character.
The first switch would handle the "Twenty", "Thirty", etc.
The second switch would handle one, two, three, etc.
You will need to have a special case for the teens that just spits out the word for each.
Just take time in your reseach. If you don't know how to do it, I would advise to parse the int number by one number and then format the text via case.
switch (int)
case 1:
cout << "one";
switch (int)
case 2:
cout << "two";
It would be easiest to just evaluate both digits separately and match them up to string values stored in two arrays.
So for example, you might have these two arrays...
tens[0] = ""
tens[1] = ""
tens[2] = "Twenty"
tens[3] = "Thirty"
tens[4] = "Forty"
tens[5] = "Fifty"
tens[6] = "Sixty"
etc...
ones[0] = ""
ones[1] = "One"
ones[2] = "Two"
ones[3] = "Three"
etc...
And then if the number is >= 20, you can simply take the first digit and use it as your index for the tens array, and your second digit and use it as your index for your ones array. If the number is between 10 and 19, you'll need some special logic to handle it.
Initialize this function
function Ones_String(number1) {
if (number1 == 1) {
string1 = "One";
} elseif (number2 == 9) {
string1 = "Nine";
} elseif (number2 == 10) {
string1 = "Ten";
} elseif (number2 == 0) {
string1 = "Zero";
} else {
string1 = ""; // empty value
}
return string1;
}
function Tens_String(number2) {
if (number2 == 2) {
string2 = "Twenty";
} elseif (number2 == 3) {
string2 = "Thirty";
} elseif (number2 == 9) {
string2 = "Ninety";
} else {
string2 = ""; // emtpy value
}
return string2;
}
function teens_string(number3) {
if (number3 == 11) {
string3 = "Eleven";
} elseif (number3 == 12) {
string3 = "Tweleve";
} else {
string3 = "Nineteen";
}
return string3;
}
If given number < 11 then call Ones_string()
If it is number >= 11 then do below logic
First : get the seconds digit value and call Tens_String();
Second : get the first digit vallue and call Ones_string();
And this algorithm applies till 99 .. Last used in 2006 at College on C++..
Whatever i mentioned is an algorithm / logic to detect.. not the perfect code

Resources