I need to select a part of a string ,suppose i have a string like this :Hello::Hi,
I use this characters :: as a separator, so i need to separate Hello and Hi.I am using C# application form .
I googled it ,i found something like substring but it didn't help me.
Best regards
string.Split is the right method, but the syntax is a little tricky when splitting based on a string versus a character.
The overload to split on a string takes the input as an array of strings so it can be distinquished from the overload that takes an array of characters (since a string can be easily cast to an array of characters), and adds a parameter for StringSplitEntries, which you can set to None to use the default option (include "empty" entries):
string source = "Hello::Hi";
string[] splits = source.Split(new string[] {"::"}, StringSplitOptions.None);
You can split a string into multiple parts based on a semaphore using the Split function:
var stringToSearch = "Hello::Hi";
var foundItems = stringToSearch.Split(new[] {"::"},
StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < foundItems.Count(); i++)
{
Console.WriteLine("Item #{0}: {1}", i + 1, foundItems[i]);
}
// Ouput:
// Item #1: Hello
// Item #2: Hi
Related
I have a string like XXXXmakeXXmodel nameXXageXX**** for a car data. I want to get make, model name and age.
So can I split this using regex or another way in c#?
You can convert the string to an array of keyword / value based on key words
for example: XXXXmakeXXmodel
Identify that it does not start with a keyword
Take the value before the keyword
Take the keyword
repeat until you have processed the entire string.
You need to use the String.IndexOf and Substring methodes.
You can split string using Split() function with a delimiter i.e. "XX".
var input = "XXXXmakeXXmodel nameXXageXX****";
//Split string by "XX" and remove empty entries
var array = input.Split("XX", StringSplitOptions.RemoveEmptyEntries);
//Take first n - 1 elements to avoid last ****
var result = array.Take(array.Length - 1);
//Print expected result.
Console.WriteLine(string.Join(Environment.NewLine, result));
.NET FIDDLE
I have this string:
com.example.is-this#myname
i would like it to be
myname#this-is.example.com
using .Net, but a straight out concept or an idea would be good to.
What i'm currently doing is going over each character, find out if it's one of the "special characters" and assign all prior chars, to a variable of an array, at the end, i'm joining them all together from last to first.
is there a possible more efficient way to do this ?
This is the classic word-by-word reversal, with a small twist on delimiters. A solution to this problem is reversing each word individually, and then reversing the whole string. Do not touch delimiters when reversing words.
First step goes as follows: we find limits of each token, and reverse it in place, like this:
com.example.is-this#myname
moc.example.is-this#myname
moc.elpmaxe.is-this#myname
moc.elpmaxe.si-this#myname
moc.elpmaxe.si-siht#myname
moc.elpmaxe.si-siht#emanym
Reverse the result to get your desired output:
moc.elpmaxe.si-siht#emanym -> myname#this-is.example.com
As far as the implementation goes, you can do it by converting the string to an array of characters to make it changeable in place, and write a short helper method that lets you reverse a portion of a char array between indexes i and j. With this helper method in place, all you need to do is to find delimiters and call the helper for each delimited word, and then make one final call to reverse the entire sentence.
With little bit of Regex and Linq this is fairly simple.
Idea is that we take words and non word characters as separate token with Regex patten. Then, we just reverse it and join it.
var tokens = Regex.Matches("com.example.is-this#myname", #"\w+|\W")
.Cast<Match>()
.Select(x=>x.Value)
.Reverse();
string reversed = string.Concat(tokens);
Output: Ideone - Demo
myname#this-is.example.com
You could use the Split C# method.
The example below is from here.
using System;
class Program
{
static void Main()
{
string s = "there is a cat";
// Split string on spaces.
// ... This will separate all the words.
string[] words = s.Split(' ');
foreach (string word in words)
{
Console.WriteLine(word);
}
}
}
Is as simple as examples get.
Then you add more conditions to your Split()
string [] split = strings .Split(new Char [] {'.' , '#', '-' },
StringSplitOptions.RemoveEmptyEntries);
The RemoveEmptyEntries just removes unwanted empty entries to your array.
After that you reverse your array using the Array.Reverse method.
And then you can stitch your string back together with a Foreach loop.
As #marjan-venema mentioned in the comments you could populate a parallel array at this point with each delimiter. Reverse it, and then concatenate the string when you are using the Foreach loop at each entry.
Here's another way to do it using a List, which has a handy Insert method, as well as a Reverse method.
The Insert method lets you continue to add characters to the same index in the list (and the others after it are moved to higher indexes).
So, as you read the original string, you can keep inserting the characters at the start. Once you come to a delimeter, you add it to the end and adjust your insert position to be right after the delimeter.
When you're done, you just call Reverse and join the characters back to a string:
public static string ReverseWords(string words, char[] wordDelimeters)
{
var reversed = new List<char>();
int insertPosition = 0;
for(int i = 0; i < words.Length; i++)
{
var character = words[i];
if (wordDelimeters.Contains(character))
{
reversed.Add(character);
insertPosition = i + 1;
continue;
}
reversed.Insert(insertPosition, character);
}
reversed.Reverse();
return string.Join("", reversed);
}
I read the *.txt file from c# and displayed in the console.
My text file looks like a table.
diwas hey
ivonne how
pokhara d kd
lekhanath when
dipisha dalli hos
dfsa sasf
Now I want to search for a string "pokhara" and if it is found then it should display the "d kd" and if not found display "Not found"
What I tried?
string[] lines = System.IO.ReadAllLines(#"C:\readme.txt");
foreach(string line in lines)
{
string [] words = line.Split();
foreach(string word in words)
{
if (word=="pokhara")
{
Console.WriteLine("Match Found");
}
}
}
My Problem:
Match was found but how to display the next word of the line. Also sometimes
in second row some words are split in two with a space, I need to show both words.
I guess your delimiter is the tab-character, then you can use String.Split and LINQ:
var lineFields = System.IO.File.ReadLines(#"C:\readme.txt")
.Select(l => l.Split('\t'));
var matches = lineFields
.Where(arr => arr.First().Trim() == "pokhara")
.Select(arr => arr.Last().Trim());
// if you just want the first match:
string result = matches.FirstOrDefault(); // is null if not found
If you don't know the delimiter as suggested by your comment you have a problem. If you don't even know the rules of how the fields are separated it's very likely that your code is incorrect. So first determine the business logic, ask the people who created the text file. Then use the correct delimiter in String.Split.
If it's a space you can either use string.Split()(without argument), that includes spaces, tabs and new-line characters or use string.Split(' ') which only includes the space. But note that is a bad delimiter if the fields can contain spaces as well. Then either use a different or wrap the fields in quoting characters like "text with spaces". But then i suggest a real text-parser like the Microsoft.VisualBasic.FileIO.TextFieldParser which can also be used in C#. It has a HasFieldsEnclosedInQuotes property.
This works ...
string[] lines = System.IO.ReadAllLines(#"C:\readme.txt");
string stringTobeDisplayed = string.Empty;
foreach(string line in lines)
{
stringTobeDisplayed = string.Empty;
string [] words = line.Split();
//I assume that the first word in every line is the key word to be found
if (word[0].Trim()=="pokhara")
{
Console.WriteLine("Match Found");
for(int i=1 ; i < words.Length ; i++)
{
stringTobeDisplayed += words[i]
}
Console.WriteLine(stringTobeDisplayed);
}
}
Okay, lets say I have a string:
string text = "one|two|three";
If I do string[] texts = text.Split('|'); I will end up with a string array of three objects. However, this isn't what I want. What I actually want is to split the string only once... so the two arrays I could would be this:
one
two|three
Additionally, is there a way to do a single split with the last occurrence in a string? So I get:
one|two
three
As well, is there a way to split by a string, instead of a character? So I could do Split("||")
Split method takes a count as parameter, you can pass 2 in that position, which basically says that you're interested in only 2 elements maximum. You'll get the expected result.
For second question: There is no built in way AFAIK. You may need to implement it yourself by splitting all and joining first and second back.
C#'s String.Split() can take a second argument that can define the number of elements to return:
string[] texts = text.Split(new char[] { '|' }, 2);
For your first scenario, you can pass a parameter of how many strings to split into.
var text = "one|two|three";
var result = text.Split(new char[] { '|' }, 2);
Your second scenario requires a little more magic.
var text = "one|two|three";
var list = text.Split('|');
var result = new string[] { string.Join("|", list, 0, list.Length - 1), list[list.Length - 1] };
Code has not been verified to check results before using.
Well, I took it as a challenge to do your second one in one line. The result is... not pretty, mostly because it's surprisingly difficult to reverse a string and keep it as a string.
string text = "one|two|three";
var result = new String(text.Reverse().ToArray()).Split(new char[] {'|'}, 2).Reverse().Select(c => new String(c.Reverse().ToArray()));
Basically, you reverse it, then follow the same procedure as the first one, then reverse each individual one, as well as the resulting array.
You can simply do like this as well...
//To split at first occurence of '|'
if(text.Containts('|')){
beginning = text.subString(0,text.IndexOf('|'));
ending = text.subString(text.IndexOf('|');
}
//To split at last occurence of '|'
if(text.Contains('|')){
beginning = text.subString(0,text.LastIndexOf('|'));
ending = text.subString(text.LastIndexOf('|');
}
Second question was fun. I solved it this way:
string text = "one|two|three";
var result =
new []
{
string.Concat(text.ToCharArray().TakeWhile((c, i) => i <= text.LastIndexOf("|"))),
string.Concat(text.ToCharArray().SkipWhile((c, i) => i <= text.LastIndexOf("|")))
};
I read strings from a file and they come in various styles:
item0 item1 item2
item0,item1,item2
item0_item1_item2
I split them like this:
string[] split_line = line[i].split(new char[] {' ',',','_'});
I change an item (column) and then i stitch the strings back together using string builder.
But now when putting the string back I have to use the right delimiter.
Is it possible to know which delimiter was used when splitting the string?
UPDATE
the caller will pass me the first item so that I only change that line.
Unless you keep track of splitting action (one at the time) you don't.
Otherwise, you could create a regular expression, to catch the item and the delimiter and go from there.
Instead of passing in an array of characters, you can use a Regex to split the string instead. The advantage of doing this, is that you can capture the splitting character. Regex.Split will insert any captures between elements in the array like so:
string[] space = Regex.Split("123 456 789", #"([,_ ])");
// Results in { "123", " ", "456", " ", "789" }
string[] comma = Regex.Split("123,456,789", #"([,_ ])");
// Results in { "123", ",", "456", ",", "789" }
string[] underscore = Regex.Split("123_456_789", #"([,_ ])");
// Results in { "123", "_", "456", "_", "789" }
Then you can edit all items in the array with something like
for (int x = 0; x < space.Length; x += 2)
space[x] = space[x] + "x";
Console.WriteLine(String.Join("", space));
// Will print: 123x 456x 789x
One thing to be wary of when dealing with multiple separators is if there are any lines that have spaces, commas and underscores in them. e.g.
37,hello world,238_3
This code will preserve all the distinct separators but your results might not be expected. e.g. the output of the above would be:
37x,hellox worldx,238x_3x
As I mentioned that the caller passes me the first item so I tried something like this:
// find the right row
if (lines[i].ToLower().StartsWith(rowID))
{
// we have to know which delim was used to split the string since this will be
// used when stitching back the string together.
for (int delim = 0; delim < delims.Length; delim++)
{
// we split the line into an array and then use the array index as our column index
split_line = lines[i].Trim().Split(delims[delim]);
// we found the right delim
if (split_line.Length > 1)
{
delim_used = delims[delim];
break;
}
}
}
basically I iterate each line over the delims and check the resulting array length. If it is > 1 that means that delim worked otherwise skip to next one. I am using split functions property "If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance."