C# - Merging strings from a certain position - c#

I want to create a function but I don't know how it would work or how to create it. I want to create a function something similar to below.
I have a string, lets say its this for example:
string myString = "This is my string and it will forever be my string.";
What if I wanted to split this by a space and get each part? which I do...
string[] parts = myString.Split(' ');
Now, I want to get everything but the first 3 words in my string parts, how would I merge each string in parts except the first 3? which will return
string and it will forever be my string.
Something similar to this:
public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{
}

public string getMergedString(string[] parts, int start) // This method would return everything from where you told it to start...
{
return String.Join(" ", parts.Skip(start));
}
Quick explanation of the code:
string.Join(separator, IEnumerable values)
This joins an IEnumerable object containing strings to one, unified string.
Docs: https://msdn.microsoft.com/en-us/library/system.string.join(v=vs.110).aspx
parts.Skip(int count)
This part of the code skips a given amount of elements, before returning them.
Skip(int count) is an extension method found in the System.Linq namespace.
You need .Net 3.5 or higher in order for you to be able to use this method.
Docs: https://msdn.microsoft.com/en-us/library/bb358985(v=vs.110).aspx

string myString = "This is my string and it will forever be my string.";
string[] words = myString.Split(' ');
var myNewString = string.Join(" ", words.Skip(3));

Related

Optimize an iteration of IEnumerable<string> [duplicate]

for long time , I always append a string in the following way.
for example if i want to get all the employee names separated by some symbol , in the below example i opeted for pipe symbol.
string final=string.Empty;
foreach(Employee emp in EmployeeList)
{
final+=emp.Name+"|"; // if i want to separate them by pipe symbol
}
at the end i do a substring and remove the last pipe symbol as it is not required
final=final.Substring(0,final.length-1);
Is there any effective way of doing this.
I don't want to appened the pipe symbol for the last item and do a substring again.
Use string.Join() and a Linq projection with Select() instead:
finalString = string.Join("|", EmployeeList.Select( x=> x.Name));
Three reasons why this approach is better:
It is much more concise and readable
– it expresses intend, not how you
want to achieve your goal (in your
case concatenating strings in a
loop). Using a simple projection with Linq also helps here.
It is optimized by the framework for
performance: In most cases string.Join() will
use a StringBuilder internally, so
you are not creating multiple strings that are
then un-referenced and must be
garbage collected. Also see: Do not
concatenate strings inside loops
You don’t have to worry about special cases. string.Join()
automatically handles the case of
the “last item” after which you do
not want another separator, again
this simplifies your code and makes
it less error prone.
I like using the aggregate function in linq, such as:
string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + ", " + next);
You should join your strings.
Example (borrowed from MSDN):
using System;
class Sample {
public static void Main() {
String[] val = {"apple", "orange", "grape", "pear"};
String sep = ", ";
String result;
Console.WriteLine("sep = '{0}'", sep);
Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]);
result = String.Join(sep, val, 1, 2);
Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result);
}
}
For building up like this, a StringBuilder is probably a better choice.
For your final pipe issue, simply leave the last append outside of the loop
int size = EmployeeList.length()
for(int i = 0; i < size - 1; i++)
{
final+=EmployeeList.getEmployee(i).Name+"|";
}
final+=EmployeeList.getEmployee(size-1).Name;

remove first element from array

PHP developer here working with c#.
I'm using a technique to remove a block of text from a large string by exploding the string into an array and then shifting the first element out of the array and turning what remains back into a string.
With PHP (an awesome & easy language) it was just
$array = explode('somestring',$string);
array_shift($array);
$newstring = implode(' ', $array);
and I'm done.
I get so mad at c# for not allowing me to create dynamic arrays and for not offering me default functions that can do the same thing as PHP regarding arrays. Instead of dynamic arrays I have to create lists and predefine key structures etc. But I'm new and I'm sure there are still equally graceful ways to do the same with c#.
Will someone show me a clean way to accomplish this goal with c#?
Rephrase of question: How can I remove the first element from an array using c# code.
Here is how far I've gotten, but RemoveAt throws a error while debugging so I don't believe it works:
//scoop-out feed header information
if (entry_start != "")
{
string[] parts = Regex.Split(this_string, #entry_start);
parts.RemoveAt(0);
this_string = String.Join(" ", parts);
}
I get so mad at c# for not allowing me to create dynamic arrays
You may take a look at the List<T> class. Its RemoveAt might be worth checking.
But for your particular scenario you could simply use LINQ and the Skip extension method (don't forget to add using System.Linq; to your file in order to bring it into scope):
if (entry_start != "")
{
string[] parts = Regex.Split(this_string, #entry_start).Skip(1).ToArray();
this_string = String.Join(" ", parts);
}
C# is not designed to be quick and dirty, nor it particularly specializes in text manipulation. Furthermore, the technique you use for removing some portion of a string from a beginning is crazy imho.
Why don't you just use String.Substring(int start, int length) coupled with String.IndexOf("your delimiter")?
Here is the corresponding C# code:
string input = "a,b,c,d,e";
string[] splitvals = input.Split(',');
string output = String.Join(",", splitvals, 1, splitvals.Length-1);
MessageBox.Show(output);
You can use LINQ for this:
if (entry_start != "")
this_string = String.Join(" ", Regex.Split(this_string, #entry_start).Skip(1).ToArray());
string split = ",";
string str = "asd1,asd2,asd3,asd4,asd5";
string[] ary = str.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries);
string newstr = string.Join(split, ary, 1, ary.Count() - 1);
splits at ",". removes the first record. then combines back with ","
As stated above, you can use LINQ. Skip(int) will return an IEnumerable<string> that you can then cast back as array.
string[] myArray = new string[]{"this", "is", "an", "array"};
myArray = myArray.Skip(1).toArray();
You might be more comfortable with generic lists than arrays, which work more like PHP arrays.
List<T>
But if your goal is "to remove a block of text from a large string" then the easier way would be:
string Example = "somestring";
string BlockRemoved = Example.Substring(1);
// BlockRemoved = "omestring"
Edit
I misunderstood the question, thinking you were just removing the first element from the array where the array consisted of the characters that make up the string.
To split a string by a delimiter, look at the String.Split method instead. Some good examples are given here.

Appending a string in a loop in effective way

for long time , I always append a string in the following way.
for example if i want to get all the employee names separated by some symbol , in the below example i opeted for pipe symbol.
string final=string.Empty;
foreach(Employee emp in EmployeeList)
{
final+=emp.Name+"|"; // if i want to separate them by pipe symbol
}
at the end i do a substring and remove the last pipe symbol as it is not required
final=final.Substring(0,final.length-1);
Is there any effective way of doing this.
I don't want to appened the pipe symbol for the last item and do a substring again.
Use string.Join() and a Linq projection with Select() instead:
finalString = string.Join("|", EmployeeList.Select( x=> x.Name));
Three reasons why this approach is better:
It is much more concise and readable
– it expresses intend, not how you
want to achieve your goal (in your
case concatenating strings in a
loop). Using a simple projection with Linq also helps here.
It is optimized by the framework for
performance: In most cases string.Join() will
use a StringBuilder internally, so
you are not creating multiple strings that are
then un-referenced and must be
garbage collected. Also see: Do not
concatenate strings inside loops
You don’t have to worry about special cases. string.Join()
automatically handles the case of
the “last item” after which you do
not want another separator, again
this simplifies your code and makes
it less error prone.
I like using the aggregate function in linq, such as:
string[] words = { "one", "two", "three" };
var res = words.Aggregate((current, next) => current + ", " + next);
You should join your strings.
Example (borrowed from MSDN):
using System;
class Sample {
public static void Main() {
String[] val = {"apple", "orange", "grape", "pear"};
String sep = ", ";
String result;
Console.WriteLine("sep = '{0}'", sep);
Console.WriteLine("val[] = {{'{0}' '{1}' '{2}' '{3}'}}", val[0], val[1], val[2], val[3]);
result = String.Join(sep, val, 1, 2);
Console.WriteLine("String.Join(sep, val, 1, 2) = '{0}'", result);
}
}
For building up like this, a StringBuilder is probably a better choice.
For your final pipe issue, simply leave the last append outside of the loop
int size = EmployeeList.length()
for(int i = 0; i < size - 1; i++)
{
final+=EmployeeList.getEmployee(i).Name+"|";
}
final+=EmployeeList.getEmployee(size-1).Name;

cutting from string in C#

My strings look like that: aaa/b/cc/dd/ee . I want to cut first part without a / . How can i do it? I have many strings and they don't have the same length. I tried to use Substring(), but what about / ?
I want to add 'aaa' to the first treeNode, 'b' to the second etc. I know how to add something to treeview, but i don't know how can i receive this parts.
Maybe the Split() method is what you're after?
string value = "aaa/b/cc/dd/ee";
string[] collection = value.Split('/');
Identifies the substrings in this instance that are delimited by one or more characters specified in an array, then places the substrings into a String array.
Based on your updates related to a TreeView (ASP.Net? WinForms?) you can do this:
foreach(string text in collection)
{
TreeNode node = new TreeNode(text);
myTreeView.Nodes.Add(node);
}
Use Substring and IndexOf to find the location of the first /
To get the first part:
// from memory, need to test :)
string output = String.Substring(inputString, 0, inputString.IndexOf("/"));
To just cut the first part:
// from memory, need to test :)
string output = String.Substring(inputString,
inputString.IndexOf("/"),
inputString.Length - inputString.IndexOf("/");
You would probably want to do:
string[] parts = "aaa/b/cc/dd/ee".Split(new char[] { '/' });
Sounds like this is a job for... Regular Expressions!
One way to do it is by using string.Split to split your string into an array, and then string.Join to make whatever parts of the array you want into a new string.
For example:
var parts = input.Split('/');
var processedInput = string.Join("/", parts.Skip(1));
This is a general approach. If you only need to do very specific processing, you can be more efficient with string.IndexOf, for example:
var processedInput = input.Substring(input.IndexOf('/') + 1);

string[] management

ok, so ill cut to the chase here. and to be clear, im looking for code examples where possible.
so, i have a normal string, lets say,
string mystring = "this is my string i want to use";
ok, now that i have my string, i split it by the space with
string[] splitArray = mystring.Split(new char[] { ' ' });
ok, so now i have splitArray[0] through splitArray[7].
now, i need to do some fancy things with the string that i normally wouldnt need to do.
here are a few:
i need to cut off the first word, so i am left with the other 7 words, so that i have something like:
string myfirstword = "this";
mystring = "is my string i want to use";
now, i will need to use mystring over and over again, using different parts of it at different times, and depending on the string i will have no idea how long, it will be. so i will give some examples of things ill need.
first, ill need to know, how many words are there (this is easy, just throwing it in)
second, ill need some way of using things like,
string secondword = splitArray[1];
string everythingAfterTheSecondWord = splitArray[2+];
if you noticed, i included a [2+] ... the + indicating that i want all strings in the array put back together, spaces in all, into a string. so for example,
string examplestring = "this is my example for my stack overflow question";
string[] splitArray2 = examplestring.Split(new char[] { ' ' });
now, if i called on splitArray2[4+] i would want a return of "for my stack overflow question". now obviously its not as simple as adding a + to a string array.. but thats what i need, and under the current situation i have tried many other easier ways that simply to not work.
ALSO, if i called on something like splitArray2[2-5] i would want, words 2 through 5 obviously.
Summary:
i need greater management of my string[] arrays, and i need to be able to find, every word after word *, need to be able to strip out random words in the string while leaving the rest of the string intact, and need to be able to find string m through n
Thanks!
Most of what you're looking for can be achieved with a List<string>. Briefly:
string mystring = "this is my string i want to use";
List<string> splitArray = new List<string>(mystring.Split(new char[] { ' ' }));
string firstWord = splitArray[0];
// mystring2 = "is my string i want to use"
splitArray.RemoveAt(0);
string mystring2 = String.Join(" ", splitArray.ToArray());
To do the more complicated things you describe with splitArray[2+] requires LINQ though, and hence .NET 3.5.
List<string> everythingAfterTheSecondWord = splitArray.Skip(2).ToList();
For splitArray[2-5]:
List<string> arraySlice = splitArray.Skip(2).Take(3).ToList();
Well, to do the "every word starting at word X" you could do this:
string newString = string.join(splitArray," ",x);
To get y words starting at x, do this:
string newString = string.join(splitArray," ",x,y);
To get the number of words:
int wordCount= splitArray.Length;
Putting it all together, words x-y goes like this:
string newString = string.join(splitArray," ",x, splitArray.Length-x+1);

Categories

Resources