String manipulation

Hi Guys,

Need some api for string comparison and for also shuffling characters in a string.

Ex: local string = "Sudheer"
shuffled string should be some thing like "herduse"..

Try this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
local function shuffleString(inputStr)
        local outputStr = "";
        local strLength = string.len(inputStr);
        
        while (strLength ~=0) do
                --get a random character of the input string
                local pos = math.random(strLength);
                
                --insert into output string
                outputStr = outputStr..string.sub(inputStr,pos,pos);
                
                --remove the used character from input string
                inputStr = inputStr:sub(1, pos-1) .. inputStr:sub(pos+1);
                
                --get new length of the input string
                strLength = string.len(inputStr);
        end
        
        return outputStr;
end
 
 
local function main()
        local testString = "Shuffle Me!!";
        print("Before Shuffle: ",testString);
        
        testString = shuffleString(testString);
        print("After Shuffle: ",testString);
end
 
--run the code:
main();

One more thing about this code, you would probsbly need to change the random seed, so you don't always get the same result.

Just add this code to the first line of the function:

1
math.randomseed( os.time() );
views:1497 update:2011/11/2 21:34:51
corona forums © 2003-2011