Split string into string array of single characters - c#

I want to something as simple as turning "this is a test" into
new string[] {"t","h","i","s"," ","i","s"," ","a"," ","t","e","s","t"}
Would I really have to do something like
test = "this is a test".Select(x => x.ToString()).ToArray();
edit: To clarify, I don't want a char array, ideally I want an array of string. I don't really see anything wrong with the above code except for the fact that I would think there is an easier way.

I believe this is what you're looking for:
char[] characters = "this is a test".ToCharArray();

Strings in C# already have a char indexer
string test = "this is a test";
Console.WriteLine(test[0]);
And...
if(test[0] == 't')
Console.WriteLine("The first letter is 't'");
This works too...
Console.WriteLine("this is a test"[0]);
And this...
foreach (char c in "this is a test")
Console.WriteLine(c);
EDIT:
I noticed the question was updated with regards to char[] arrays. If you must have a string[] array, here's how you split a string at each character in c#:
string[] test = Regex.Split("this is a test", string.Empty);
foreach (string s in test)
{
Console.WriteLine(s);
}

Simple!!
one line:
var res = test.Select(x => new string(x, 1)).ToArray();

Try this:
var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());

You can just use String.ToCharArray() and then treat each char as a string in your code.
Here's an example:
foreach (char c in s.ToCharArray())
Debug.Log("one character ... " +c);

Most likely you're looking for the ToCharArray() method. However, you will need to do slightly more work if a string[] is required, as you noted in your post.
string str = "this is a test.";
char[] charArray = str.ToCharArray();
string[] strArray = str.Select(x => x.ToString()).ToArray();
Edit: If you're worried about the conciseness of the conversion, I suggest you make it into an extension method.
public static class StringExtensions
{
public static string[] ToStringArray(this string s)
{
if (string.IsNullOrEmpty(s))
return null;
return s.Select(x => x.ToString()).ToArray();
}
}

Convert the message to a character array, then use a for loop to change it to a string
string message = "This Is A Test";
string[] result = new string[message.Length];
char[] temp = new char[message.Length];
temp = message.ToCharArray();
for (int i = 0; i < message.Length - 1; i++)
{
result[i] = Convert.ToString(temp[i]);
}

string input = "this is a test";
string[] afterSplit = input.Split();
foreach (var word in afterSplit)
Console.WriteLine(word);
Result:
this
is
a
test

Related

Separating string on each character and putting it in an array

I'm pulling a string from a MySQL database containing all ID's from friends in this format:
5+6+12+33+1+9+
Now, whenever i have to add a friend it's simple, I just take the the string and add whatever ID and a "+". My problem lies with separating all the ID's and putting it in an array. I'm currently using this method
string InputString = "5+6+12+33+1+9+";
string CurrentID = string.Empty;
List<string> AllIDs = new List<string>();
for (int i = 0; i < InputString.Length; i++)
{
if (InputString.Substring(i,1) != "+")
{
CurrentID += InputString.Substring(i, 1);
}
else
{
AllIDs.Add(CurrentID);
CurrentID = string.Empty;
}
}
string[] SeparatedIDs = AllIDs.ToArray();
Even though this does work it just seems overly complicated for what i'm trying to do.
Is there an easier way to split strings or cleaner ?
Try this:-
var result = InputString.Split(new char[] { '+' });
You can use other overloads of Split
as well if you want to remove empty spaces.
You should to use the Split method with StringSplitOptions.RemoveEmptyEntries. RemoveEmptyEntries helps you to avoid empty string as the last array element.
Example:
char[] delimeters = new[] { '+' };
string InputString = "5+6+12+33+1+9+";
string[] SeparatedIDs = InputString.Split(delimeters,
StringSplitOptions.RemoveEmptyEntries);
foreach (string SeparatedID in SeparatedIDs)
Console.WriteLine(SeparatedID);
string[] IDs = InputString.Split('+'); will split your InputString into an array of strings using the + character
var result = InputString.Split('+', StringSplitOptions.RemoveEmptyEntries);
extra options needed since there is a trailing +

Parsing a string with, seemingly, no delimiter

I have the following string that I need to parse out so I can insert them into a DB. The delimiter is "`":
`020 Some Description `060 A Different Description `100 And Yet Another `
I split the string into an array using this
var responseArray = response.Split('`');
So then each item in the responseArrray[] looks like this: 020 Some Description
How would I get the two different parts out of that array? The 1st part will be either 3 or 4 characters long. 2nd part will be no more then 35 characters long.
Due to some ridiculous strangeness beyond my control there is random amounts of space between the 1st and 2nd part.
Or put the other two answers together, and get something that's more complete:
string[] response = input.Split(`);
foreach (String str in response) {
int splitIndex = str.IndexOf(' ');
string num = str.Substring(0, splitIndex);
string desc = str.Substring(splitIndex);
desc.Trim();
}
so, basically you use the first space as a delimiter to create 2 strings. Then you trim the second one, since trim only applies to leading and trailing spaces, not everything in between.
Edit: this a straight implementation of Brad M's comment.
You can try this solution:
var inputString = "`020 Some Description `060 A Different Description `100 And Yet Another `";
int firstWordLength = 3;
int secondWordMaxLength = 35;
var result =inputString.Split('`')
.SelectMany(x => new[]
{
new String(x.Take(firstWordLength).ToArray()).Trim(),
new String(x.Skip(firstWordLength).Take(secondWordMaxLength).ToArray()).Trim()
});
Here is the result in LINQPad:
Update: My first solution has some problems because the use of Trim after Take.Here is another approach with an extension method:
public static class Extensions
{
public static IEnumerable<string> GetWords(this string source,int firstWordLengt,int secondWordLenght)
{
List<string> words = new List<string>();
foreach (var word in source.Split(new[] {'`'}, StringSplitOptions.RemoveEmptyEntries))
{
var parts = word.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
words.Add(new string(parts[0].Take(firstWordLengt).ToArray()));
words.Add(new string(string.Join(" ",parts.Skip(1)).Take(secondWordLenght).ToArray()));
}
return words;
}
}
And here is the test result:
Try this
string response = "020 Some Description060 A Different Description 100 And Yet Another";
var responseArray = response.Split('`');
string[] splitArray = {};
string result = "";
foreach (string it in responseArray)
{
splitArray = it.Split(' ');
foreach (string ot in splitArray)
{
if (!string.IsNullOrWhiteSpace(ot))
result += "-" + ot.Trim();
}
}
splitArray = result.Substring(1).Split('-');
string[] entries = input.Split('`');
foreach (string s in entries)
GetStringParts(s);
IEnumerable<String> GetStringParts(String input)
{
foreach (string s in input.Split(' ')
yield return s.Trim();
}
Trim only removes leading/trailing whitespace per MSDN, so spaces in the description won't hurt you.
If the first part is an integer
And you need to account for some empty
For me the first pass was empty
public void parse()
{
string s = #"`020 Some Description `060 A Different Description `100 And Yet Another `";
Int32 first;
String second;
if (s.Contains('`'))
{
foreach (string firstSecond in s.Split('`'))
{
System.Diagnostics.Debug.WriteLine(firstSecond);
if (!string.IsNullOrEmpty(firstSecond))
{
firstSecond.TrimStart();
Int32 firstSpace = firstSecond.IndexOf(' ');
if (firstSpace > 0)
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(0, firstSpace) + "'");
if (Int32.TryParse(firstSecond.Substring(0, firstSpace), out first))
{
System.Diagnostics.Debug.WriteLine("'" + firstSecond.Substring(firstSpace-1) + "'");
second = firstSecond.Substring(firstSpace).Trim();
}
}
}
}
}
}
You can get the first part by finding the first space and make a substring. The second is also a Substring. Try something like this.
foreach(string st in response)
{
int index = response.IndexOf(' ');
string firstPart = response.Substring(0, index);
//string secondPart = response.Substring(response.Lenght-35);
//better use this
string secondPart = response.Substring(index);
secondPart.Trim();
}

Trim a string in c# after special character

I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);

To fetch the unique characters from a string?

I want to extract unique characters from a string. For example:- 'AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ' will return 'ABCFGDJ'
I have tried below piece of code but now I want to optimize it.
Please suggest if anyone knows.
static string extract(string original)
{
List<char> characters = new List<char>();
string unique = string.Empty;
foreach (char letter in original.ToCharArray())
{
if (!characters.Contains(letter))
{
characters.Add(letter);
}
}
foreach (char letter in characters)
{
unique += letter;
}
return unique;
}
I don't know if this is faster, but surely shorter
string s = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";
var newstr = String.Join("", s.Distinct());
Another LINQ approach, but not using string.Join:
var result = new string(original.Distinct().ToArray());
I honestly don't know which approach to string creation would be faster. It probably depends on whether string.Join ends up internally converting each element to a string before appending to a StringBuilder, or whether it has custom support for some well-known types to avoid that.
How about
var result = string.Join("", "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ".Distinct());
Make sure that you include System.Linq namespace.
Try this
string str = "AAABBBBBCCCCFFFFGGGGGDDDDJJJJJJ";
string answer = new String(str.Distinct().ToArray());
I hope this helps.
if "AAABBBAAA" should return "ABA", then the following does it. Albeit not very fast.
List<char> no_repeats = new List<char>();
no_repeats.Add(s[0]);
for (int i = 1; i < s.Length; i++)
{
if (s[i] != no_repeats.Last()) no_repeats.Add(s[i]);
}
string result = string.Join("", no_repeats);

How to split string that delimiters remain in the end of result?

I have several delimiters. For example {del1, del2, del3 }.
Suppose I have text : Text1 del1 text2 del2 text3 del3
I want to split string in such way:
Text1 del1
text2 del2
text3 del3
I need to get array of strings, when every element of array is texti deli.
How can I do this in C# ?
String.Split allows multiple split-delimeters. I don't know if that fits your question though.
Example :
String text = "Test;Test1:Test2#Test3";
var split = text.Split(';', ':', '#');
//split contains an array of "Test", "Test1", "Test2", "Test3"
Edit: you can use a regex to keep the delimeters.
String text = "Test;Test1:Test2#Test3";
var split = Regex.Split(text, #"(?<=[;:#])");
// contains "Test;", "Test1:", "Test2#","Test3"
This should do the trick:
const string input = "text1-text2;text3-text4-text5;text6--";
const string matcher= "(-|;)";
string[] substrings = Regex.Split(input, matcher);
StringBuilder builder = new StringBuilder();
foreach (string entry in substrings)
{
builder.Append(entry);
}
Console.Out.WriteLine(builder.ToString());
note that you will receive empty strings in your substring array for the matches for the two '-';s at the end, you can choose to ignore or do what you like with those values.
You could use a regex. For a string like this "text1;text2|text3^" you could use this:
(.*;|.*\||.*\^)
Just add more alternative pattens for each delimiter.
If you want to keep the delimiter when splitting the string you can use the following:
string[] delimiters = { "del1", "del2", "del3" };
string input = "text1del1text2del2text3del3";
string[] parts = input.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
for(int index = 0; index < parts.Length; index++)
{
string part = parts[index];
string temp = input.Substring(input.IndexOf(part) + part.Length);
foreach (string delimter in delimiters)
{
if ( temp.IndexOf(delimter) == 0)
{
parts[index] += delimter;
break;
}
}
}
parts will then be:
[0] "text1del1"
[1] "text2del2"
[2] "text3del3"
As #Matt Burland suggested, use Regex
List<string> values = new List<string>();
string s = "abc123;def456-hijk,";
Regex r = new Regex(#"(.*;|.*-|.*,)");
foreach(Match m in r.Matches(s))
values.Add(m.Value);

Categories

Resources