I have byte[] array Q that contains some data.To convert the array to string I'm using result=System.Text.Encoding.ASCII.GetString(Q); The result is something like JOBID: 196035002\n .I need only the integer part of it. Is there a way to get only the int value 196035002 without converting to string and splitting into another array?
I think the language you are talking about is C#. What you need to do is:
char[] delimiterChars = { ':' };
string[] words = result.Split(delimiterChars);
foreach (string s in words)
{
System.Console.WriteLine(s);
}
If you don't want to use functions like Split then you can try this regex to get the desired output.
String inputString = "JOBID: 196035002\n";
Int32 result = Convert.ToInt32(Regex.Match(inputString, #"\d+").Value);
NameSpace for Regex: using System.Text.RegularExpressions;
Related
string a = "100-0-6-7-6-10-8-" //and so on
/////////////////////////////////////////////
//my solution
char[] delimiterChars = {'-'};
string solution = "100-0-6-7-6-10-8-";
string[] words = solution.Split(delimiterChars,System.StringSplitOptions.RemoveEmptyEntries);
//ok so i encounter some problems when trying to overwrite 0s, and 10s,100s etc
//so when writing data to the "solution" string it should be
//"-100--0--6--7--6--10--8-" instead of "100-0-6-7-6-10-8-"
basically, I want to separate each number and put it in a list or array
i think i got it
char[] delimiterChars = {'-'};
string text = "100-0-6-7-6-10-8-";
string[] words = text.Split(delimiterChars,System.StringSplitOptions.RemoveEmptyEntries);
This solution using Linq works as well.
var text="100-0-6-7-6-10-8-";
var words=text.Split("-").Where(x => !string.IsNullOrEmpty(x)).ToArray();
This question already has answers here:
Convert a list of strings to a single string
(6 answers)
Closed 6 years ago.
I'm new to C#, and apologies for the noob question - I'm trying to convert a list of strings to a single string so I can use it with WWWForm's POST function.
If I have a list of strings (e.g. kidIds = ["a#123", "b#123"]), how do I easily convert it to a single string ("a#123, b#123")? In Javascript, I would simply do kidIds.join(","), but I'm not sure how to do it in C#.
I tried doing kidIds.ToArray().ToString(), but it's not really giving me what I want. I could loop through the entire list using a for loop, but I was wondering if there's a simpler one liner I could use?
Since you are new to C# I would like to tell you that, you were trying to convert a list of strings to a single string. No it is not a list of string but it is a array of string. List of strings would be initalize like
List<string> SomeName = new List<string>();
Where as your one is declared as array. Now you can Join the Array of strings into one string as same as Javascript like
string SomeString = String.Join(",", kidIds);
The string.Join method combines many strings into one. It receives two arguments: an array (or IEnumerable) and a separator string.
You can also create one string out of the String array using + that would concatenate the strings like
string smstr = String.Empty;
for(int i=0; i<kidIds.Length; i++)
{
smstr = smstr + kidIds[i];
//or
smstr += kidIds[i]
}
You can also choose StringBuilder to create one string out of array of strings since StringBuilder.Append() method is much better than using the + operator like
StringBuilder sb = new StringBuilder();
for(int i=0;i<kidIds.Length;i++)
{
sb.Append(kidIds[i]);
}
But StringBuilder is good when the concatenations are less than 1000, String.Join() is even more efficient than StringBuilder.
There is basically the same thing as JavaScript's join()
String.Join Method
Use String.Join(',', kidIds);
https://msdn.microsoft.com/en-us/library/tk0xe5h0(v=vs.110).aspx
Perhaps you can try the function concat, like
String str = "";
str = kidIds[0] + kidIds[1];
or
str = str.concat(kidIds[0], kidIds[0]);
or
for(int i=0;i<length;i++)
{
str += kidIds[i];
}
I think i would help.
You can do this using following code...
string[] kidIds = { "a#123", "b#123" };
String str = "";
foreach (var kidId in kidIds)
{
str += kidId + ",";
}
str = str.Remove(str.Length - 1,1); // this line use for remove last comma
thanks...
Ok, so I know that questions LIKE this have been asked a lot on here, but I can't seem to make solutions work.
I am trying to take a string from a file and find the longest word in that string.
Simples.
I think the issue is down to whether I am calling my methods on a string[] or char[], currently stringOfWords returns a char[].
I am trying to then order by descending length and get the first value but am getting an ArgumentNullException on the OrderByDescending method.
Any input much appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace TextExercises
{
class Program
{
static void Main(string[] args)
{
var fileText = File.ReadAllText(#"C:\Users\RichardsPC\Documents\TestText.txt");
var stringOfWords = fileText.ToArray();
Console.WriteLine("Text in file: " + fileText);
Console.WriteLine("Words in text: " + fileText.Split(' ').Length);
// This is where I am trying to solve the problem
var finalValue = stringOfWords.OrderByDescending(n => n.length).First();
Console.WriteLine("Largest word is: " + finalValue);
}
}
}
Don't split the string, use a Regex
If you care about performance you don't want to split the string. The reason in order to do the split method will have to traverse the entire string, create new strings for the items it finds to split and put them into an array, computational cost of more than N, then doing an order by you do another (at least) O(nLog(n)) steps.
You can use a Regex for this, which will be more efficient, because it will only iterate over the string once
var regex = new Regex(#"(\w+)\s",RegexOptions.Compiled);
var match = regex.Match(fileText);
var currentLargestString = "";
while(match.Success)
{
if(match.Groups[1].Value.Length>currentLargestString.Length)
{
currentLargestString = match.Groups[1].Value;
}
match = match.NextMatch();
}
The nice thing about this is that you don't need to break the string up all at once to do the analysis and if you need to load the file incrementally is a fairly easy change to just persist the word in an object and call it against multiple strings
If you're set on using an Array don't order by just iterate over
You don't need to do an order by your just looking for the largest item, computational complexity of order by is in most cases O(nLog(n)), iterating over the list has a complexity of O(n)
var largest = "";
foreach(var item in strArr)
{
if(item.Length>largest.Length)
largest = item;
}
Method ToArray() in this case returns char[] which is an array of individual characters. But instead you need an array of individual words. You can get it like this:
string[] stringOfWords = fileText.Split(' ');
And you have a typo in your lambda expression (uppercase L):
n => n.Length
Try this:
var fileText = File.ReadAllText(#"C:\Users\RichardsPC\Documents\TestText.txt");
var words = fileText.Split(' ')
var finalValue = fileText.OrderByDescending(n=> n.Length).First();
Console.WriteLine("Longest word: " + finalValue");
As suggested in the other answer, you need to split your string.
string[] stringOfWords = fileText.split(new Char [] {',' , ' ' });
//all is well, now let's loop over it and see which is the biggest
int biggest = 0;
int biggestIndex = 0;
for(int i=0; i<stringOfWords.length; i++) {
if(biggest < stringOfWords[i].length) {
biggest = stringOfWords[i].length;
biggestIndex = i;
}
}
return stringOfWords[i];
What we're doing here is splitting the string based on whitespace (' '), or commas- you can add an unlimited number of delimiters there - each word, then, gets its own space in the array.
From there, we're iterating over the array. If we encounter a word that's longer than the current longest word, we update it.
I have what seemed at first to be a trivial problem but turned out to become something I can't figure out how to easily solve. I need to be able to store lists of items in a string. Then those items in turn can be a list, or some other value that may contain my separator character. I have two different methods that unpack the two different cases but I realized I need to encode the contained value from any separator characters used with string.Split.
To illustrate the problem:
string[] nested = { "mary;john;carl", "dog;cat;fish", "plainValue" }
string list = string.Join(";", nested);
string[] unnested = list.Split(';'); // EEK! returns 7 items, expected 3!
This would produce a list "mary;john;carl;dog;cat;fish;plainValue", a value I can't split to get the three original nested strings from. Indeed, instead of the three original strings, I'd get 7 strings on split and this approach thus doesn't work at all.
What I want is to allow the values in my string to be encoded so I can unpack/split the contents just the way before I packed/join them. I assume I might need to go away from string.Split and string.Join and that is perfectly fine. I might just have overlooked some useful class or method.
How can I allow any string values to be packed / unpacked into lists?
I prefer neat, simple solutions over bulky if possible.
For the curious mind, I am making extensions for PlayerPrefs in Unity3D, and I can only work with ints, floats and strings. Thus I chose strings to be my data carrier. This is why I am making this nested list of strings.
try:
const char joinChar = '╗'; // make char const
string[] nested = { "mary;john;carl", "dog;cat;fish", "plainValue" };
string list = string.Join(Convert.ToString(joinChar), nested);
string[] unnested = list.Split(joinChar); // eureka returns 3!
using an ascii character outside the normal 'set' allows you to join and split without ruining your logic that is separated on the ; char.
Encode your strings with base64 encoding before joining.
The expected items are 7 because you're splitting with a ; char. I would suggest to change your code to:
string[] nested = { "mary;john;carl", "dog;cat;fish", "plainValue" }
string list = string.Join("#" nested);
string[] unnested = list.Split('#'); // 3 strings again
Have you considered using a different separator, eg "|"?
This way the joined string will be "mary;john;carl|dog;cat;fish|plainValue" and when you call list.split("|"); it will return the three original strings
Use some other value than semicolon (;) for joining. For example - you can use comma (,) and you will get "mary;john;carl,dog;cat;fish,plainValue". When you again split it based on (,) as a separator, you should get back your original string value.
I came up with a solution of my own as well.
I could encode the length of an item, followed with the contents of an item. It would not use string.Split and string.Join at all, but it would solve my problem. The content would be untouched, and any content that need encoding could in turn use this encoding in its content space.
To illustrate the format (constant length header):
< content length > < raw content >
To illustrate the format (variable length header):
< content length > < header stop character > < raw content >
In the former, a fixed length of characters are used to describe the length of the contents. This could be plain text, hexadecimal, base64 or some other encoding.
Example with 4 hexadecimals (ffff/65535 max length):
0005Hello0005World
In the latter example, we can reduce this to:
5:Hello5:World
Then I could look for the first occurance of : and parse the length first, to extract the substring that follows. After that is the next item of the list.
A nested example could look like:
e:5:Hello5:Worlda:2:Hi4:John
(List - 14 charactes including headers)
Hello (5 characters)
World (5 characters)
(List - 10 characters including headers)
Hi (2 characters)
John (4 characters)
A drawback is that it explicitly requires the length of all items, even if no "shared separator" character wouldn't been present (this solution use no separators if using fixed length header).
Maby not as nice as you wanted. But here goes :)
static void Main(string[] args)
{
string[] str = new string[] {"From;niklas;to;lasse", "another;day;at;work;", "Bobo;wants;candy"};
string compiledString = GetAsString(str);
string[] backAgain = BackToStringArray(compiledString);
}
public static string GetAsString(string[] strings)
{
string returnString = string.Empty;
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(ms))
{
writer.Write(strings.Length);
for (int i = 0; i < strings.Length; ++i)
{
writer.Write(strings[i]);
}
}
ms.Flush();
byte[] array = ms.ToArray();
returnString = Encoding.UTF8.GetString(array);
}
return returnString;
}
public static string[] BackToStringArray(string encodedString)
{
string[] returnStrings = new string[0];
byte[] toBytes = Encoding.UTF8.GetBytes(encodedString);
using (MemoryStream stream = new MemoryStream(toBytes))
{
using (BinaryReader reader = new BinaryReader(stream))
{
int numStrings = reader.ReadInt32();
returnStrings = new string[numStrings];
for (int i = 0; i < numStrings; ++i)
{
returnStrings[i] = reader.ReadString();
}
}
}
return returnStrings;
}
I have to port some C# code to Java and I am having some trouble converting a string splitting command.
While the actual regex is still correct, when splitting in C# the regex tokens are part of the resulting string[], but in Java the regex tokens are removed.
What is the easiest way to keep the split-on tokens?
Here is an example of C# code that works the way I want it:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String[] values = Regex.Split("5+10", #"([\+\-\*\(\)\^\\/])");
foreach (String value in values)
Console.WriteLine(value);
}
}
Produces:
5
+
10
I don't know how C# does it, but to accomplish it in Java, you'll have to approximate it. Look at how this code does it:
public String[] split(String text) {
if (text == null) {
text = "";
}
int last_match = 0;
LinkedList<String> splitted = new LinkedList<String>();
Matcher m = this.pattern.matcher(text);
// Iterate trough each match
while (m.find()) {
// Text since last match
splitted.add(text.substring(last_match,m.start()));
// The delimiter itself
if (this.keep_delimiters) {
splitted.add(m.group());
}
last_match = m.end();
}
// Trailing text
splitted.add(text.substring(last_match));
return splitted.toArray(new String[splitted.size()]);
}
This is because you are capturing the split token. C# takes this as a hint that you wish to retain the token itself as a member of the resulting array. Java does not support this.