I have googled but just no luck.
I want to chop the first character of a string like this:
string s = "hello, world";
string t = cast(string) s[1..$]; // OK
string u = s[1..$]; // ERROR, can't cast char[] to string.
Well, I may miss something. cast(string)
make the code more unreadable.
Is there any easier way to get the substring (without cast)?
Well, if you really don't want to use substrings, you can use String's toCharArray() method, then you can use a StringBuilder to append the chars. With this you can loop through each of the array's indices.
Suffix - A substring that comes at the end of the string. Formally, s is a suffix of t iff ∃w ∈ Σ*(t = ws) Proper - A proper substring is any substring s of t where s ≠ t. Likewise, you can also have a proper prefix and a proper suffix. ϵ is a substring, prefix, and suffix of every string.
A substring is a subset or part of another string, or it is a contiguous sequence of characters within a string. For example, "Substring" is a substring of "Substring in Java."
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
You shouldn't have to cast there at all, these are all strings.
If s is a char[]
, you might be able to force it to be string by specifying it (like you did in the example), or use to!string(s)
to convert it. to!string
is found in the module std.conv
.
After you have everything of consistent types, when doing substrings, slicing is good, like you are doing there, but you might want to be a little careful if there's non-ascii characters in it. string[1 .. $] chops off the first byte, but a character might be multiple bytes.
If you import std.utf;
, you'll have a function called stride
available which can check for multi byte characters.
string t = s[s.stride() .. $]; // chops off the first character*, even if it is multi-byte
Generally, though, I'd say get the index with other functions, then slice it. So if you want to substring world, do:
import std.string;
auto index = s.indexOf("world");
if(index == -1) throw new Exception("substring 'world' not found");
auto world = s[index .. $]; // gets the substring starting from world to the end of string
Functions like indexOf
can handle the complications of multi-byte characters for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With