Is there any way to convert a string ("abcdef") to an array of string containing its character (["a","b","c","d","e","f"]) without using the String.Split function?
So you want an array of string, one char each:
string s = "abcdef";
string[] a = s.Select(c => c.ToString()).ToArray();
This works because string implements IEnumerable<char>. So Select(c => c.ToString()) projects each char in the string to a string representing that char and ToArray enumerates the projection and converts the result to an array of string.
If you're using an older version of C#:
string s = "abcdef";
string[] a = new string[s.Length];
for(int i = 0; i < s.Length; i++) {
a[i] = s[i].ToString();
}
Yes.
"abcdef".ToCharArray();
You could use linq and do:
string value = "abcdef";
string[] letters = value.Select(c => c.ToString()).ToArray();
This would get you an array of strings instead of an array of chars.
Why don't you just
string value="abcd";
value.ToCharArray();
textbox1.Text=Convert.toString(value[0]);
to show the first letter of the string; that would be 'a' in this case.
Bit more bulk than those above but i don't see any simple one liner for this.
List<string> results = new List<string>;
foreach(Char c in "abcdef".ToCharArray())
{
results.add(c.ToString());
}
results.ToArray(); <-- done
What's wrong with string.split???
Related
I have a string array, I want to access the characters of the first element in that array:
string[] str= new string[num];
for(int i = 0; i < num; i++)
{
str[i] = Console.ReadLine();
}
To access the characters of the first element in the string array, in Java
str[0].CharAt[0] // 1st character
Is there a way in C# for this? The only function I could see was use of substring. It will incur more overhead in such case.
You would use:
str[0][0]
where the first [0] is accessing the 0th array member, while the next [0] is the indexer defined by System.String which gives the 0th char value (UTF-16 code unit) of the string.
Yes, you can do that:
string[] s = new string[]{"something", "somethingMore"};
char c = s[0][0];
You could convert the first string of the string array to a character array and simply get the first value of the character array.
string[] stringArray = {"abc"};
char[] charArray = stringArray[0].ToCharArray();
char first = charArray[0];
Am looking for the code which need to convert string to int array so far what i done is :
string text = "[1,2]";
int[] ia = text.Split(';').Select(n => Convert.ToInt32(n)).ToArray();
But am getting number format exception how to get rid of this here is the string "[1,2]" need to convert into [1,2] how can i achieve this it may be dumb question but need to solve this.
Just a piece of cake using JsonConvert,
int[] arr = JsonConvert.DeserializeObject<int[]>(text);
Just Trim the string's '[' and ']' and split by ',' to get it as array.
Then convert it to int array using 'Array.ConvertAll' method.
string s = "[1,2]";
string[] s1 = s.Trim('[', ']').Split(',');
int[] myArr = Array.ConvertAll(s1, n => int.Parse(n));
Replace the braces [] with empty string and then apply Split function.
objModellead.ServiceCatalogID
.Replace("[","")
.Replace("]","")
.Split(';')
.Select(int.Parse)
.ToArray()
I am trying to parse a string into array and find a very concise approach.
string line = "[1, 2, 3]";
string[] input = line.Substring(1, line.Length - 2).Split();
int[] num = input.Skip(2)
.Select(y => int.Parse(y))
.ToArray();
I tried remove Skip(2) and I cannot get the array because of non-int string. My question is that what is the execution order of those LINQ function. How many times is Skip called here?
Thanks in advance.
The order is the order that you specify. So input.Skip(2) skips the first two strings in the array, so only the last remains which is 3. That can be parsed to an int. If you remove the Skip(2) you are trying to parse all of them. That doesn't work because the commas are still there. You have splitted by white-spaces but not removed the commas.
You could use line.Trim('[', ']').Split(','); and int.TryParse:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int i = 0;
int[] num = input.Where(s => int.TryParse(s, out i)) // you could use s.Trim but the spaces don't hurt
.Select(s => i)
.ToArray();
Just to clarify, i have used int.TryParse only to make sure that you don't get an exception if the input contains invalid data. It doesn't fix anything. It would also work with int.Parse.
Update: as has been proved by Eric Lippert in the comment section using int.TryParse in a LINQ query can be harmful. So it's better to use a helper method that encapsulates int.TryParse and returns a Nullable<int>. So an extension like this:
public static int? TryGetInt32(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Now you can use it in a LINQ query in this way:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int[] num = input.Select(s => s.TryGetInt32())
.Where(n => n.HasValue)
.Select(n=> n.Value)
.ToArray();
The reason it does not work unless you skip the first two lines is that these lines have commas after ints. Your input looks like this:
"1," "2," "3"
Only the last entry can be parsed as an int; the initial two will produce an exception.
Passing comma and space as separators to Split will fix the problem:
string[] input = line
.Substring(1, line.Length - 2)
.Split(new[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);
Note the use of StringSplitOptions.RemoveEmptyEntries to remove empty strings caused by both comma and space being used between entries.
I think it would be better you do it this way:
JsonConvert.DeserializeObject(line, typeof(List<int>));
you might try
string line = "[1,2,3]";
IEnumerable<int> intValues = from i in line.Split(',')
select Convert.ToInt32(i.Trim('[', ' ', ']'));
In Java there is a method splitByCharacterType that takes a string, for example 0015j8*(, and split it into "0015","j","8","*","(". Is there a built in function like this in c#? If not how would I go around building a function to do this?
public static IEnumerable<string> SplitByCharacterType(string input)
{
if (String.IsNullOrEmpty(input))
throw new ArgumentNullException(nameof(input));
StringBuilder segment = new StringBuilder();
segment.Append(input[0]);
var current = Char.GetUnicodeCategory(input[0]);
for (int i = 1; i < input.Length; i++)
{
var next = Char.GetUnicodeCategory(input[i]);
if (next == current)
{
segment.Append(input[i]);
}
else
{
yield return segment.ToString();
segment.Clear();
segment.Append(input[i]);
current = next;
}
}
yield return segment.ToString();
}
Usage as follows:
string[] split = SplitByCharacterType("0015j8*(").ToArray();
And the result is "0015","j","8","*","("
I recommend you implement as an extension method.
I don't think that such method exist. You can follow steps as below to create your own utility method:
Create a list to hold split strings
Define strings with all your character types e.g.
string numberString = "0123456789";
string specialChars = "~!##$%^&*(){}|\/?";
string alphaChars = "abcde....XYZ";
Define a variable to hold the temporary string
Define a variable to note the type of chars
Traverse your string, one char at a time, check the type of char by checking the presence of the char in predefined type strings.
If type is new than the previous type(check the type variable value) then add the temporary string(not empty) to the list, assign the new type to type variable and assign the current char to the temp string. If otherwise, then append the char to temporary string.
In the end of traversal, add the temporary string(not empty) to the list
Now your list contains the split strings.
Convert the list to an string array and you are done.
You could maybe use regex class, somthing like below, but you will need to add support for other chars other than numbers and letters.
var chars = Regex.Matches("0015j8*(", #"((?:""[^""\\]*(?:\\.[^""\\]*)*"")|[a-z]|\d+)").Cast<Match>().Select(match => match.Value).ToArray();
Result
0015,J,8
how can I convert a char to a char* in c#?
I'm initializeing a String object like this:
String test=new String('c');
and I'm getting this error:
Argument '1': cannot convert from 'char' to 'char*'
That is a bit of a strange way to initialize a string, if you know beforehand what you want to store in it.
You can simply use:
String test="c";
If you have a specific need to convert a char variable to a string, you can use the built in ToString() function:
String test = myCharVariable.ToString();
unsafe
{
char c = 'c';
char *ch = &c;
}
Your example has a String and a compile error from using one of the String constructor overloads, so I'm guessing you really just want an array of chars, aka a String and maybe not a char*.
In which case:
char c = 'c';
string s = c.ToString(); // or...
string s1 = "" +c;
Also available:
unsafe
{
char c = 'c';
char* ch = &c;
string s1 = new string(ch);
string s2 = new string(c, 0);
}
string myString1 = new string(new char[] {'a'});
string myString2 = 'a'.ToString();
string myString3 = "a";
string myString4 = new string('a', 1);
unsafe {
char a = 'a';
string myString5 = new string(&a);
}
There is no overload of the public constructor for String that accepts a single char as a parameter. The closest match is
public String(char c, int count)
which creates a new String that repeats the char c count times. Thus, you could say
string s = new string('c', 1);
There are other options. There is a public constructor of String that accepts a char[] as a parameter:
public String(char[] value)
This will create a String that is initialized with the Unicode characters in value. Thus you could say
char c = 'c';
string s = new String(new char[] { c });
Another option is to say
char c = 'c'
string s = c.ToString();
But the most straightforward approach that most will expect to see is
string s = "c";
As for converting a char to a char * you can not safely do this. If you want to use the overload of the public constructor for String that accepts a char * as a parameter, you could do this:
unsafe {
char c = 'c';
char *p = &c;
string s = new string(p);
}
Can't hurt to have yet another answer:
string test = string.Empty + 'c';
The String class has many constructors, if all you're after is to create a string containing one character, you can use the following:
String test = new String(new char[] { 'c' });
If you are hard coding it, is there a reason you cant just use:
String test = "c";
How about:
var test = 'c'.ToString()
When using a char in the String constructor, you should also give a count parameter to specify how many times that character should be added to the string:
String test=new String('c', 1);
See also here.
use
String test("Something");
String test = new String(new char[]{'c'});
The easiest way to do this conversion from your example is just change the type of quotes you are using from single quotes
String test = new String('c');
to double quotes and remove the constructor call:
String test = "c";
char c = 'R';
char *pc = &c;
Using single quotes (as in your question: 'c') means that you are creating a char. Using double quotes, e.g. "c", means you creating a string. These are not interchangable types in c#.
A char*, as you might be aware, is how strings are represented in c++ to some extent, and c# supports some of the conventions of c++. This means that a char* can easily (for the programmer at least) be converted to a string in c#. Unfortunately a char is not inherently a char*, so the same cannot be done.