'Get the beginning of a string until a given char
I know that is a simple question but I couldn't find the answer.
I have this string:
"M1[r2][r3]"
I want to get only the "M1"
, I'm looking for something like strchr()
a function that get the string and a char
to stop at.
Solution 1:[1]
What about using strtok
and "["
as a delimiter?
#include <string.h> /* for strtok */
#include <stdio.h> /* for printf */
int main()
{
char str[] = "M1[r2][r3]"; // str will be modified by strtok
const char deli[] = "["; // deli could also be declared as [2] or as const char *. Take your pick...
char *token;
token = strtok(str, deli); // can also call strtok(str, "["); and not use variable deli at all
printf("%s", token); // printf("%s", str); will print the same result
/* OUTPUT: M1 */
return 0;
}
Solution 2:[2]
Use strtok()
and the character to stop (a delimeter, in your case [
) like this:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="M1[r2][r3]";
printf ("Getting M1 from \"%s\":\n",str);
strtok (str,"[");
if (str != NULL)
printf ("%s\n",str);
return 0;
}
Output:
Getting M1 from "M1[r2][r3]":
M1
However, if you know the length of the substring, you should see Get a substring of a char*.
Solution 3:[3]
something like strchr() a function that get the string and a char to stop at.
If only a printing of the sub-string is needed, use strcspn()
which finds the offset when '['
first occurs, (or the end if not found). This does not alter the source string.
const char *s = "M1[r2][r3]";
printf("%.*s\n", (int) strcspn(s, "["), s);
Output
M1
Solution 4:[4]
Use sscanf()
like this:
char subStr[3];
sscanf("M1[r2][r3]", " %2[^[]", subStr);
where [^[]
means a character except [
and 2 guards the length of the string written into the substring (it's equal to subStr
's size - 1, so that space for the NULL terminator is available).
as BLUEPIXY suggested.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | gsamaras |
Solution 3 | |
Solution 4 |