Joining strings
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class MainClass
{
public static void Main()
{
string[] s = new string[] { "J", "M", "P", "C" };
string joined = String.Join("|", s);
Console.WriteLine(joined);
}
}
J|M|P|C
Split strings by three tokens
using System;
class MainClass {
public static void Main() {
string str = "while if for, public class do.";
char[] seps = {" ", ".", "," };
// Split the string into parts.
string[] parts = str.Split(seps);
Console.WriteLine("Pieces from split: ");
for(int i=0; i < parts.Length; i++)
Console.WriteLine(parts[i]);
}
}
Pieces from split:
while
if
for
public
class
do
Split string with \\
using System;
class Class1
{
[STAThread]
static void Main(string[] args)
{
char delim = "\\";
string filePath = "C:\\Windows\\Temp";
string [] directories = null;
directories = filePath.Split( delim );
foreach (string directory in directories)
{
Console.WriteLine("{0}", directory);
}
}
}
Splitting strings by |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
public class MainClass
{
public static void Main()
{
string s = "J|M|P|C";
string[] pieces = s.Split("|");
foreach (string piece in pieces)
{
Console.WriteLine(piece);
}
}
}
J
M
P
C
String joins
using System;
class MainClass {
public static void Main() {
string str = "while if for, public class do.";
char[] seps = {" ", ".", "," };
// Split the string into parts.
string[] parts = str.Split(seps);
string whole = String.Join(" | ", parts);
Console.WriteLine("Result of join: ");
Console.WriteLine(whole);
}
}
Result of join:
while | if | for | | public | class | do |
String Split
using System;
public class MainClass
{
static void Main()
{
string s1 = "One,Two,Three Associates, Inc.";
const char Space = " ";
const char Comma = ",";
char[] delimiters = new char[] {Space, Comma};
foreach (string subString in s1.Split (delimiters))
{
Console.WriteLine(subString);
}
}
}
Tokenize strings
using System;
class MainClass {
public static void Main() {
string[] input = {
"100 + 19",
"100 - 87"
};
char[] seps = {" "};
for(int i=0; i < input.Length; i++) {
string[] parts = input[i].Split(seps);
Console.Write("Command: ");
for(int j=0; j < parts.Length; j++)
Console.Write(parts[j] + " ");
}
}
}
Command: 100 + 19 Command: 100 - 87