If I have string like:
String^ str ="hhB2LWq50a+9HZiNLKuwdQ==.pdf aaaaaaaa bbbbbbbbb cccccdddddeee ffffffgggghhh";
and I want to extract the first part of it which is
hhB2LWq50a+9HZiNLKuwdQ==.pdf
How can do that in C++/CLI or C# ?
You can use String.Split() method
string str ="hhB2LWq50a+9HZiNLKuwdQ==.pdf aaaaaaaa bbbbbbbbb cccccdddddeee";
string[] parts = str.Split(' ');
if (parts != null)
{
string firstPart = parts[0];
}
Or using LINQ First():
using System.Linq;
string firstPart = str.Split(' ').First();
Use string.IndexOf to find the first space, then string.Substring to copy:
string str ="hhB2LWq50a+9HZiNLKuwdQ==.pdf aaaaaaaa bbbbbbbbb cccccdddddeee";
int spacePos = str.IndexOf(' ');
if (spacePos == -1)
return null;
else
return str.Substring(0, spacePos);
This assumes that the string doesn't have any leading spaces. If it can have leading spaces, you should probably call Trim on it first.
in C# it's so easy
string tem = "test test";
string[] s = tem.Split(' ');
Console.WriteLine(s[0]);
Console.ReadLine();
you can use regular expression to parse your string and extract the desire text
Related
I would like to know how can i remove characters in a string from a specific index like :
string str = "this/is/an/example"
I want to remove all characters from the third '/' including so it would be like this:
str = "this/is/an"
I tried with substring and regex but i cant find a solution.
Using string operations:
str = str.Substring(0, str.IndexOf('/', str.IndexOf('/', str.IndexOf('/') + 1) + 1));
Using regex:
str = Regex.Replace(str, #"^(([^/]*/){2}[^/]*)/.*$", "$1");
To get "this/is/an":
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/'));
If you need to keep the slash:
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/')+1);
This expects there to be at least one slash. If none are present, you should check it beforehand to not throw an exception:
string str = "this.s.an.example";
string newStr = str;
if (str.Contains('/'))
newStr = str.Remove(str.LastIndexOf('/'));
If its importaint to get the third one, make a dynamic method for it, like this. Input the string, and which "folder" you want returned. 3 in your example will return "this/is/an":
static string ReturnNdir(string sDir, int n)
{
while (sDir.Count(s => s == '/') > n - 1)
sDir = sDir.Remove(sDir.LastIndexOf('/'));
return sDir;
}
This regex is the answer: ^[^/]*\/[^/]*\/[^/]*. It will capture the first three chunks.
var regex = new Regex("^[^/]*\\/[^/]*\\/[^/]*", RegexOptions.Compiled);
var value = regex.Match(str).Value;
I think the best way of doing that it's creating a extension
string str = "this/is/an/example";
str = str.RemoveLastWord();
//specifying a character
string str2 = "this.is.an.example";
str2 = str2.RemoveLastWord(".");
With this static class:
public static class StringExtension
{
public static string RemoveLastWord(this string value, string separator = "")
{
if (string.IsNullOrWhiteSpace(value))
return string.Empty;
if (string.IsNullOrWhiteSpace(separator))
separator = "/";
var words = value.Split(Char.Parse(separator));
if (words.Length == 1)
return value;
value = string.Join(separator, words.Take(words.Length - 1));
return value;
}
}
I have string string text = "1.2788923 is a decimal number. 1243818 is an integer. "; Is there a way to split it on the commas only ? This means to split on ". " but not on '.'. When I try string[] sentences = text.Split(". "); I get method has invalid arguments error..
Use String.Split Method (String[], StringSplitOptions) to split it like:
string[] sentences = text.Split(new string[] { ". " },StringSplitOptions.None);
You will end up with two items in your string:
1.2788923 is a decimal number
1243818 is an integer
You can use Regex.Split:
string[] parts = Regex.Split(text, #"\. ");
The string(s) that you splitting on are expected to be in a separate array.
String[] s = new String[] { ". " };
String[] r = "1. 23425".Split(s, StringSplitOptions.None);
Use Regular Expressions
public static void textSplitter(String text)
{
string pattern = "\. ";
String[] sentences = Regex.Split(text, pattern);
}
I have a string like '/Test1/Test2', and i need to take Test2 separated from the same. How can i do that in c# ?
Try this:
string toSplit= "/Test1/Test2";
toSplit.Split('/');
or
toSplit.Split(new [] {'/'}, System.StringSplitOptions.RemoveEmptyEntries);
to split, the latter will remove the empty string.
Adding .Last() will get you the last item.
e.g.
toSplit.Split('/').Last();
Use .Split().
string foo = "/Test1/Test2";
string extractedString = foo.Split('/').Last(); // Result Test2
This site have quite a few examples of splitting strings in C#. It's worth a read.
Using .Split and a little bit of LINQ, you could do the following
string str = "/Test1/Test2";
string desiredValue = str.Split('/').Last();
Otherwise you could do
string str = "/Test1/Test2";
string desiredValue = str;
if(str.Contains("/"))
desiredValue = str.Substring(str.LastIndexOf("/") + 1);
Thanks Binary Worrier, forgot that you'd want to drop the '/', darn fenceposts
string[] arr = string1.split('/');
string result = arr[arr.length - 1];
string [] split = words.Split('/');
This will give you an array split that will contain "", "Test1" and "Test2".
If you just want the Test2 portion, try this:
string fullTest = "/Test1/Test2";
string test2 = test.Split('/').ElementAt(1); //This will grab the second element.
string inputString = "/Test1/Test2";
string[] stringSeparators = new string[] { "/Test1/"};
string[] result;
result = inputString.Split(stringSeparators,
StringSplitOptions.RemoveEmptyEntries);
foreach (string s in result)
{
Console.Write("{0}",s);
}
OUTPUT : Test2
what is the efficient mechanism to remove 2 or more white spaces from a string leaving single white space.
I mean if string is "a____b" the output must be "a_b".
You can use a regular expression to replace multiple spaces:
s = Regex.Replace(s, " {2,}", " ");
Something like below maybe:
var b=a.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
var noMultipleSpaces = string.Join(" ",b);
string tempo = "this is a string with spaces";
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(#"[ ]{2,}", options);
tempo = regex.Replace(tempo, #" ");
You Can user this method n pass your string value as argument
you have to add one namespace also using System.Text.RegularExpressions;
public static string RemoveMultipleWhiteSpace(string str)
{
// A.
// Create the Regex.
Regex r = new Regex(#"\s+");
// B.
// Remove multiple spaces.
string s3 = r.Replace(str, #" ");
return s3;
}
I want to split a string into an array. The string is as follows:
:hello:mr.zoghal:
I would like to split it as follows:
hello mr.zoghal
I tried ...
string[] split = string.Split(new Char[] {':'});
and now I want to have:
string something = hello ;
string something1 = mr.zoghal;
How can I accomplish this?
String myString = ":hello:mr.zoghal:";
string[] split = myString.Split(':');
string newString = string.Empty;
foreach(String s in split) {
newString += "something = " + s + "; ";
}
Your output would be:
something = hello; something = mr.zoghal;
For your original request:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
var somethings = split.Select(s => String.Format("something = {0};", s));
Console.WriteLine(String.Join("\n", somethings.ToArray()));
This will produce
something = hello;
something = mr.zoghal;
in accordance to your request.
Also, the line
string[] split = string.Split(new Char[] {':'});
is not legal C#. String.Split is an instance-level method whereas your current code is either trying to invoke Split on an instance named string (not legal as "string" is a reserved keyword) or is trying to invoke a static method named Split on the class String (there is no such method).
Edit: It isn't exactly clear what you are asking. But I think that this will give you what you want:
string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
string something = split[0];
string something1 = split[1];
Now you will have
something == "hello"
and
something1 == "mr.zoghal"
both evaluate as true. Is this what you are looking for?
It is much easier than that. There is already an option.
string mystring = ":hello:mr.zoghal:";
string[] split = mystring.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries);