OCaml splitting bytes vs characters - string

It seems I'm a little confused on the best way to handle this. At the moment I am using Jane Street's Core. Split has a signature that looks like
split : t -> on:char -> t list
Which is fine. However, I noticed that any string I type is a "Bytes" type. This creates a problem when I try to split because it expects a char. My question is, what is the best way to handle this? Right now I'm doing
String.split "My string is here" (String.get " " 0)
But this seems very hacky. I feel like there should be a better solution to this. Can anyone help me? Thank you!

You can make a char using 's.
# "x";;
- : string = "x"
# 'x';;
- : char = x
# String.split "My string is here" ' ';;
- : string list = ["My"; "string"; "is"; "here"]

It's possible to use regexp to solve your problem :
let () =
let l = Str.split (Str.regexp_string " ") "My string is here" in
List.iter (Printf.printf "%s\n") l

Related

Converting a string to bytes

im fairly new to OCaml, so excuse any stupid mistake.
Im trying to modify the elements of a string, yet it wont allow me, saying it is expecting an expression of type bytes. After doing some reading, I know why, so I tried to convert my string to bytes, with no success. I've looked everywhere on how to convert a string to bytes, but can't seem to find anything. Can someone help me?
There is a function Bytes.of_string that does this.
Bytes.of_string "my string abc";;
- : bytes = Bytes.of_string "my string abc"
It's interesting to note that the toplevel expression printer (the P part of REPL) prints byte values using a Bytes.of_string call.
You can convert back to a string with Bytes.to_string.
# let b = Bytes.of_string "hal9000";;
val b : bytes = Bytes.of_string "hal9000"
# Bytes.to_string (Bytes.map (fun c -> Char.chr (Char.code c + 1)) b);;
- : string = "ibm:111"

Java program to find which string is replaced by which string?

String s1="Welcome To Java";
String s2="Wela To Java";
Write a Java program to get the output that come is replaced by a.
If you are sure that that is one char replacing multi chars, you can use this:
String s1="Welcome To Java";
String s2="Wela To Java";
for (int i = 1; i < s2.length()+1; i++){
char c = s2.charAt(i-1);
String part1= s2.substring (0,i-1);
String part2=s2.substring(i);
if (s1.contains(part1)&&(s1.contains(part2))){
int t1 = s1.lastIndexOf(part1)+part1.length();
int t2 = s1.indexOf(part2);
System.out.println("Found "+s1.substring(t1,t2)+ " is replaced by "+c);
}
}
Assuming your question is replace all instances of the word 'come' with 'a', you should read up pattern-matching and the .replace() method in Java. See the docs for this:
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(java.lang.CharSequence,%20java.lang.CharSequence)
The above works nicely for either a specific string or more general patterns in the data you're working with.
P.S. Your question is unlikely to get a good answer because it's a pretty straightforward thing that requires just a quick search. I can tell you now that asking on Stack Overflow as a last resort is a good policy to follow.

Reverse the order of words in a String in Kotlin

I am looking for way to reverse the order of words in a string in Kotlin.
For example, the input string would be:
What is up, Pal!
And the output string would be:
Pal! up, is What
I know I need to use the reversed module, but I am not sure how.
You are correct in assuming that the reversed module would be helpful in this task.
However to reverse the order of the words you would also need to use things like split and joinToString (or implement them yourself):
fun reverseOrderOfWords(s: String) = s.split(" ").reversed().joinToString(" ")
val s = "What is up, Pal!"
println(reverseOrderOfWords(s))
Output:
Pal! up, is What
You could try this:
fun reverse(str:String) = str.split(" ").reduce{acc, x -> x + " " + acc}

D: Split string from the second occurrence of the character

I need to do splitting string before the second occurrence ("-").
Example: s1-qwe-123
need to get: s1-qwe
What is the best practice?
Ehm, thanks, but faced with situation where some files have structure like:
s1-123. And I need to get from them: s1.
Is there any way to make variant with split process such situation?
int saw;
auto s = "s1-qwe-123".findSplitBefore!(c => c == '-' && saw++ > 0)[0];
You could split it and join it together again.
string line = "s1-qwe-123";
string interestedBit = line.split("-")[0..2].join("-");
Or a loop through the chars:
int idx;
bool found;
string line = "s1-qwe-123";
for(idx = 0; idx < line.length; ++idx){
if(line[idx] == '-')
if(found)
break;
else
found = true;
}
auto interestedBit = line[0..idx];
My original answer was completely wrong as I misread the question. Here is a correct answer that provides a slight variation on the split solution already suggested in other answers:
import std.algorithm : splitter;
import std.array : join;
import std.range : take;
auto res = "s1-qwe-123".splitter("-").take(2).join('-');
assert(res == "s1-qwe");
The advantage of using splitter over split is lazy evaluation. This should only walk up to the second '-' and no further.
There are many ways to achieve this, I'll present two.
The first would be to split the whole string by "-" and then to join the first two elements:
import std.stdio, std.string;
"s1-qwe-123".split("-")[0 .. 2]
.join("-")
.writeln; // -> "s1-qwe"
This is simple but may not be efficient enough as the whole string has to be read. The other method I would propose is to use regular expressions as there is a matchFirst function that reads the string only up to the first occurence of the expression.
import std.stdio, std.regex;
"s1-qwe-123".matchFirst("[^-]+-[^-]+")[0]
.writeln; // -> "s1-qwe"
And if you want it to be really fast you can use a compile-time regular expression:
import std.stdio, std.regex;
"s1-qwe-123".matchFirst(ctRegex!("[^-]+-[^-]+"))[0]
.writeln; // -> "s1-qwe"

String manipulation in Lua: Swap characters in a string

I'm trying to do a function in Lua that swaps the characters in a string.
Can somebody help me ?
Here is an example:
Input = "This LIBRARY should work with any string!"
Result = "htsil biaryrs ohlu dowkrw ti hna ytsirgn!"
Note: The space is also swapped
Thank You Very Much :)
The simplest and clearest solution is this:
Result = Input:gsub("(.)(.)","%2%1")
This should do it:
input = "This LIBRARY should work with any string!"
function swapAlternateChars(str)
local t={}
-- Iterate through the string two at a time
for i=1,#str,2 do
first = str:sub(i,i)
second = str:sub(i+1,i+1)
t[i] = second
t[i+1] = first
end
return table.concat(t)
end
print(input)
print(swapAlternateChars(input))
Prints:
This LIBRARY should work with any string!
hTsiL BIARYRs ohlu dowkrw ti hna ytsirgn!
If you need the output as lower case you could always end it with:
output = swapAlternateChars(input)
print(string.lower(output))
Note, in this example, I'm not actually editing the string itself, since strings in Lua are immutable. Here's a read: Modifying a character in a string in Lua
I've used a table to avoid overhead from concatenating to a string because each concatenation may allocate a new string in memory.

Resources