How to separate string to more than one part C# - c#

I have a string, that contains links. Example:
www.google.com;www.yahoo.com;www.gmail.com
My question is how can I separate those links so I can add to all the links the tag <a> and in the end of the link the tag </a>?
I should get this:
<a>www.google.com</a>;<a>www.yahoo.com</a>;<a>www.gmail.com</a>
I will be thankful if the solution will be simple as possible and use the IndexOf method.

That code should do the job:
var input = "www.google.com;www.yahoo.com;www.gmail.com";
var result = string.Join(";", input.Split(';').Select(x => string.Format("<a>{0}</a>",x)));

var links = "www.google.com;www.yahoo.com;www.gmail.com";
var result = String.Join(";", links.Split(';').Select(s => String.Format("<a>{0}</a>", s)));

Try something like this:
var result = String.Join(";",
"www.google.com;www.yahoo.com;www.gmail.com"
.Split(';')
.Select(str => String.Format("<a>{0}</a>", str)));

The easiest way:
var result = "<a>" + String.Join("</a>;<a>", input.Split(new char[] { ';' })) + "</a>";
However, it will return <a></a> for empty input.
Explanation:
input.Split(new char[] { ';' }) splits input string by : character.
String.Join("</a>;<a>", input.Split(new char[] { ';' })) joins elements from the split using </a>;<a> string.
"<a>" + String.Join("</a>;<a>", input.Split(new char[] { ';' })) + "</a>"; adds additional <a> in front and </a> at the end of results.

Use split() function . Split string by character ; and store in an array.
string[] arr = inputstring.Split(';');
string outputstring=string.Empty;
for(int i=0;i<arr.Length;i++)
outputstring += "<a>"+arr[i]+"</a>;";
Since you don't want semicolon at end
outputstring = outputstring .TrimEnd(';');

Related

C# Concat multiline string

I got two strings A and B.
string A = #"Hello_
Hello_
Hello_";
string B = #"World
World
World";
I want to add these two strings together with a function call which could look like this:
string AB = ConcatMultilineString(A, B)
The function should return:
#"Hello_World
Hello_World
Hello_World"
The best way to do this for me was splitting the strings into an array of lines and then adding all lines together with "\r\n" and then returning it. But that seems bad practice to me since mulitple lines are not always indicated with "\r\n".
Is there a way to do this which is more reliable?
For a one line solution:
var output = string.Join(System.Environment.NewLine, A.Split('\n')
.Zip(B.Split('\n'), (a,b) => string.Join("", a, b)));
We split on \n because regardless of whether it's \n\r or just \n, it will contain \n. Left over \r seem to be ignored, but you can add a call to Trim for a and b if you feel safer for it.
Environment.NewLine is a platform-agnostic alternative to using "\r\n".
Environment.NewLine might be helpful to resolve the "mulitple lines are not always indicated with "\r\n""-issue
https://msdn.microsoft.com/de-de/library/system.environment.newline(v=vs.110).aspx
Edit:
If you dont know if multiple lines are separated as "\n" or "\r\n" this might help:
input.Split(new string[] {"\n", "\r\n"}, StringSplitOptions.RemoveEmptyEntries);
Empty lines are removed. If you dont want this use: StringSplitOptions.None instead.
See also here: How to split strings on carriage return with C#?
This does as you asked:
static string ConcatMultilineString(string a, string b)
{
string splitOn = "\r\n|\r|\n";
string[] p = Regex.Split(a, splitOn);
string[] q = Regex.Split(b, splitOn);
return string.Join("\r\n", p.Zip(q, (u, v) => u + v));
}
static void Main(string[] args)
{
string A = "Hello_\rHello_\r\nHello_";
string B = "World\r\nWorld\nWorld";
Console.WriteLine(ConcatMultilineString(A, B));
Console.ReadLine();
}
Outputs:
Hello_World
Hello_World
Hello_World
I think a generic way is very impossible, if you will load the string that is created from different platforms (Linux + Mac + Windows) or even get strings that contain HTML Line Breaks or what so ever
I think you will have to define the line break you self.
string a = getA();
string b = getB();
char[] lineBreakers = {'\r', '\n'};
char replaceWith = '\n';
foreach(string lineBreaker in lineBreakers)
{
a.Replace(lineBreaker, replaceWith);
b.Replace(lineBreaker, replaceWith);
}
string[] as = a.Split(replaceWith);
string[] bs = a.Split(replaceWith);
string newLine = Environment.NewLine;
if(as.Length == bs.Length)
{
return as.Zip(bs (p, q) => $"{p}{q}{newLine }")
}

Can you split a string and keep the split char(s)?

Is there a way to split a string but keep the split char(s), if you do this:
"A+B+C+D+E+F+G+H".Split(new char[] { '+' });
you get
A
B
C
D
E
F
G
H
Is there a way to use split so it would keep the split char:
A
+B
+C
+D
+E
+F
+G
+H
or if you were to have + in front of A then
+A
+B
+C
+D
+E
+F
+G
+H
You can use Regex.Split with a pattern that doesn't consume delimiter characters:
var pattern = #"(?=\+)";
var ans = Regex.Split(src, pattern);
This will create an empty entry if there is a leading + as there is an implied split before the +.
You could use LINQ to remove the empty entries if they aren't wanted:
var ans2 = Regex.Split(src, pattern).Where(s => !String.IsNullOrEmpty(s)).ToArray();
Alternatively, you could use Regex.Matches to extract the full matching patterns:
var ans3 = Regex.Matches(src, #"\+[^+]*").Cast<Match>().Select(m => m.Value).ToArray();
You could do:
"A+B+C+D+E+F+G+H".Split(new char[] { '+' }).Select(x => "+" + x);

Not Trimming white spaces from a string in c#

Trim() Function Not Working Please Help its not trimming the white space.
string samplestring = "172-6573-4955";
string[] array = samplestring .Split('-');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));
array[1] = restOfArray.Trim(); // providing value "6573 4955"
The scenario is I am splitting string and merging 2nd and last index into one but it's merging with white spaces.
Trim() removes whitespace from the front and back of a string, not in the middle. The whitespaces in the middle are being inserted by the " " provided as the parameter to Join() method. You could provide string.empty instead.
Trim is used to remove all leading and trailing white-space. And you want to trim the white space from middle. You may try like this:
string restOfArray = string.Join("", array.Skip(1));
or better:
string restOfArray = string.Join(string.Empty, array.Skip(1));
instead of
string restOfArray = string.Join(" ", array.Skip(1));
Trim is working as expected. Taken from String.Trim Method:
Removes all leading and trailing white-space characters from the
current String object.
The possible solutions for you are :
string restOfArray = string.Join(string.Empty, array.Skip(1));
Or
array[1] = restOfArray.Replace(" ", string.Empty).Trim();
To just split the first n-let from the rest use an additional array or you will end up with spurious data. And join with the correct separator you used in split(-):
string restOfArray = string.Join("-", array.Skip(1));
string[] result = new string[] { firstElem, restOfArray };
You don't need Trim().
You can simplify your code this way:
string[] splitCode(string code)
{
string[] segments;
segments = code.Split('-');
return new string[] { segments.First(), string.Join("-", segments.Skip(1)) };
}
Trim really isn't need here; you can simply split the string and join the parts you want:
string source = "172-6573-4955";
string[] splitter = new string[] {"-"};
string[] result;
result = source.Split(splitter, StringSplitOptions.None);
string final = (result[1] + result[2]);
Console.Write(final);
Result:
65734955
Try this:
string samplestring = "172-6573-4955";
string[] array = samplestring.Split(new char[] {'-'},2);
string result = array[1].Replace("-","");
Also, for your question about randomly putting spaces, can u pls explain "randomly" here.

Losing characters in strings after performing a split with RegEx

I want to split a string into 2 strings,
my string looks like:
HAMAN*3 whitespaces*409991
I want to have two strings the first with 'HAMAN' and the second should contain '409991'
PROBLEM: My second string has '09991' instead of '409991' after implementing this code:
string str = "HAMAN 409991 ";
string[] result = Regex.Split(str, #"\s4");
foreach (var item in result)
{
MessageBox.Show(item.ToString());
}
CURRENT SOLUTION with PROBLEM:
Split my original string when I find whitespace followed by the number 4. The character '4' is missing in the second string.
PREFERED SOLUTION:
To split when I find 3 whitespaces followed by the digit 4. And have '4' mentioned in my second string.
Try this
string[] result = Regex.Split(str, #"\s{3,}(?=4)");
Here is the Demo
Positive lookahead is your friend:
Regex.Split(str, #"\s+(?=4)");
Or you could not use Regex:
var str = "HAMAN 409991 ";
var result = str.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
EXAMPLE
Alternative if you need it to start with SPACESPACESPACE4:
var str = new[] {
"HAMAN 409991 ",
"HAMAN 409991",
"HAMAN 509991"
};
foreach (var s in str)
{
var result = s.Trim()
.Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries)
.Select(a => a.Trim())
.ToList();
if (result.Count != 2 || !result[1].StartsWith("4"))
continue;
Console.WriteLine("{0}, {1}", result[0], result[1]);
}
That's because you're splitting including the 4. If you want to split by three-consecutive-spaces then you should specify exactly that:
string[] result = Regex.Split(str, #"\s{3}");

Split a string by word using one of any or all delimiters?

I may have just hit the point where i;m overthinking it, but I'm wondering: is there a way to designate a list of special characters that should all be considered delimiters, then splitting a string using that list? Example:
"battlestar.galactica-season 1"
should be returned as
battlestar galactica season 1
i'm thinking regex but i'm kinda flustered at the moment, been staring at it for too long.
EDIT:
Thanks guys for confirming my suspicion that i was overthinking it lol: here is what i ended up with:
//remove the delimiter
string[] tempString = fileTitle.Split(#"\/.-<>".ToCharArray());
fileTitle = "";
foreach (string part in tempString)
{
fileTitle += part + " ";
}
return fileTitle;
I suppose i could just replace delimiters with " " spaces as well... i will select an answer as soon as the timer is up!
The built-in String.Split method can take a collection of characters as delimiters.
string s = "battlestar.galactica-season 1";
string[] words = s.split('.', '-');
The standard split method does that for you. It takes an array of characters:
public string[] Split(
params char[] separator
)
You can just call an overload of split:
myString.Split(new char[] { '.', '-', ' ' }, StringSplitOptions.RemoveEmptyEntries);
The char array is a list of delimiters to split on.
"battlestar.galactica-season 1".Split(new string[] { ".", "-" }, StringSplitOptions.RemoveEmptyEntries);
This may not be complete but something like this.
string value = "battlestar.galactica-season 1"
char[] delimiters = new char[] { '\r', '\n', '.', '-' };
string[] parts = value.Split(delimiters,
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < parts.Length; i++)
{
Console.WriteLine(parts[i]);
}
Are you trying to split the string (make multiple strings) or do you just want to replace the special characters with a space as your example might also suggest (make 1 altered string).
For the first option just see the other answers :)
If you want to replace you could use
string title = "battlestar.galactica-season 1".Replace('.', ' ').Replace('-', ' ');
For more information split with easy examples you may see following Url:
This also include split on words (multiple chars).
C# Split Function explained

Categories

Resources