I need to get a characters after certain character match in a string. Please consider my Input string with expected resultant character set.
Sample String
*This is a string *with more than *one blocks *of values.
Resultant string
Twoo
I have done this
string[] SubIndex = aut.TagValue.Split('*');
string SubInd = "";
foreach (var a in SubIndex)
{
SubInd = SubInd + a.Substring(0,1);
}
Any help to this will be appreciated.
Thanks
LINQ solution:
var str = "*This is a string *with more than *one blocks *of values.";
var chars = str.Split(new char[] {'*'}, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.First());
var output = String.Join("", chars);
string s = "*This is a string *with more than *one blocks *of values.";
string[] splitted = s.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
string result = "";
foreach (string split in splitted)
result += split[0];
Console.WriteLine(result);
Below code should work
var s = "*This is a string *with more than *one blocks *of values."
while ((i = s.IndexOf('*', i)) != -1)
{
// Print out the next char
if(i<s.Length)
Console.WriteLine(s[i+1]);
// Increment the index.
i++;
}
String.Join("",input.Split(new char[]{'*'},StringSplitOptions.RemoveEmptyEntries)
.Select(x=>x.First())
);
string strRegex = #"(?<=\*).";
Regex myRegex = new Regex(strRegex, RegexOptions.Multiline | RegexOptions.Singleline);
string strTargetString = "*This is a string *with more than *one blocks *of values.";
StringBuilder sb = new StringBuilder();
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success) sb.Append(myMatch.Value);
}
string result = sb.ToString();
please see below...
char[] s3 = "*This is a string *with more than *one blocks *of values.".ToCharArray();
StringBuilder s4 = new StringBuilder();
for (int i = 0; i < s3.Length - 1; i++)
{
if (s3[i] == '*')
s4.Append(s3[i+1]);
}
Console.WriteLine(s4.ToString());
Related
This question already exists:
C# split string but keep split chars / separators [duplicate]
Closed 4 years ago.
Is there a clever way to do the following string manipulation in C#?
I have any kind of string and im looking for a specified delimiter. The code should divide the string in words before and after delimiter and also include the delimiter. The delimiter could be several times in a row and also could be in the start or the end.
// PSEUDO CODE
string = "Hello****wide****world";
delimiter = "****";
// result should be a list<string> like
{"Hello","****","wide","****","world"}
You can try to use Regex and the pattern is (\*{4}).
string data = "Hello****wide****world";
string[] words = Regex.Split(data, #"(\*{4})");
List<string> result = words.ToList();
NOTE
* is a keyword in regex string, so you need to use \ to escape it.
c# online
i'll say split the string with the delimiter, then when creating the result add the delimiter after each item in the array.
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
List<string> result = new List<string>();
foreach(var item in listOfWords){
result.Add(item);
result.Add(delimiter);
}
return result;
You can do it like this. In the end, you can iterate over the result.
string input = "Hello****wide****world";
string delimiter = "****";
var listOfWords = input.Split(new string[] { delimiter }, StringSplitOptions.None);
List<string> result = new List<string>();
foreach (var item in listOfWords)
{
if (!item.Equals(listOfWords.Last()))
{
result.Add(item);
result.Add(delimiter);
}
else
{
result.Add(item);
}
}
untested
string[] words = Regex.Split(originalString, #"(?=****)");
List<string> wordsLst = words.ToList();
User Regex to do it :
string input = "Hello****wide****world";
string pattern = "(****)";
string[] substrings = Regex.Split(input, pattern);
string fullWord = "Hello****wide****world";
string delimiter = "****";
var listOfWords = fullWord.Split(delimiter);
StringBuilder result = new StringBuilder("");
result.Append("{");
foreach(var item in listOfWords){
if (!item.Equals(listOfWords.Last()))
{
result.Append($"\"{item}\",\"{delimiter}\",");
}
else
{
result.Append($"\"{item}\"");
}
}
result.Append("}");
var stringResult=result.ToString();
I have this data into the test text file:
behzad razzaqi xezerlooot abrizii ast
i want delete space and replace space one semicolon character,write this code in c# for that:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
if (!string.IsNullOrEmpty(line) && line.Length > 1)
{
sw.WriteLine(line.Replace(" ", ";"));
}
}
}
MessageBox.Show("ok");
behzad;;razzaqi;;xezerlooot;;;abrizii;;;;;ast
but i want one semicolon in space.how can i solve that?
Regex is an option:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
if (!string.IsNullOrEmpty(line) && line.Length > 1)
{
sw.WriteLine(Regex.Replace(line,#"\s+",";"));
}
}
}
MessageBox.Show("ok");
Use this code:
string[] allLines = File.ReadAllLines(#"d:\test.txt");
using (StreamWriter sw = new StreamWriter(#"d:\test.txt"))
{
foreach (string line in allLines)
{
string[] words = line.Split(" ", StringSplitOptions.RemoveEmptyEntries);
string joined = String.Join(";", words);
sw.WriteLine(joined);
}
}
You need to use a regular expression:
(\s\s+)
Usage
var input = "behzad razzaqi xezerlooot abrizii ast";
var pattern = "(\s\s+)";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, ';');
You can do that with a regular expression.
using System.Text.RegularExpressions;
and:
string pattern = "\\s+";
string replacement = ";";
Regex rgx = new Regex(pattern);
sw.WriteLine(rgx.Replace(line, replacement));
This regular expression matches any series of 1 or more spaces and replaces the entire series with a semicolon.
you can try this
Regex r=new Regex(#"\s+");
string result=r.Replace("YourString",";");
\s+ is for matching all spaces. + is for one or more occurrences.
for more information on regular expression see http://www.w3schools.com/jsref/jsref_obj_regexp.asp
You should check a string length after replacement, not before ;-).
const string file = #"d:\test.txt";
var result = File.ReadAllLines(file).Select(line => Regex.Replace(line, #"\s+", ";"));
File.WriteAllLines(file, result.Where(line => line.Length > 1));
...and don't forget, that for input hello you will get ;hello;.
I need to use a string for path for a file but sometimes there are forbidden characters in this string and I must replace them. For example, my string _title is rumbaton jonathan \"racko\" contreras.
Well I should replace the chars \ and ".
I tried this but it doesn't work:
_title.Replace(#"/", "");
_title.Replace(#"\", "");
_title.Replace(#"*", "");
_title.Replace(#"?", "");
_title.Replace(#"<", "");
_title.Replace(#">", "");
_title.Replace(#"|", "");
Since strings are immutable, the Replace method returns a new string, it doesn't modify the instance you are calling it on. So try this:
_title = _title
.Replace(#"/", "")
.Replace(#"""", "")
.Replace(#"*", "")
.Replace(#"?", "")
.Replace(#"<", "")
.Replace(#">", "")
.Replace(#"|", "");
Also if you want to replace " make sure you have properly escaped it.
Try regex
string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
illegal = r.Replace(illegal, "");
Before: "M"\a/ry/ h**ad:>> a/:?"| litt|le|| la"mb.?
After: Mary had a little lamb.
Also another answer from same post is much cleaner
private static string CleanFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
from How to remove illegal characters from path and filenames?
Or you could try this (probably terribly inefficient) method:
string inputString = #"File ~!##$%^&*()_+|`1234567890-=\[];',./{}:""<>? name";
var badchars = Path.GetInvalidFileNameChars();
foreach (var c in badchars)
inputString = inputString.Replace(c.ToString(), "");
The result will be:
File ~!##$%^&()_+`1234567890-=[];',.{} name
But feel free to add more chars to the badchars before running the foreach loop on them.
See http://msdn.microsoft.com/cs-cz/library/fk49wtc1.aspx:
Returns a string that is equivalent to the current string except that all instances of oldValue are replaced with newValue.
I have written a method to do the exact operation that you want and with much cleaner code.
The method
public static string Delete(this string target, string samples) {
if (string.IsNullOrEmpty(target) || string.IsNullOrEmpty(samples))
return target;
var tar = target.ToCharArray();
const char deletechar = '♣'; //a char that most likely never to be used in the input
for (var i = 0; i < tar.Length; i++) {
for (var j = 0; j < samples.Length; j++) {
if (tar[i] == samples[j]) {
tar[i] = deletechar;
break;
}
}
}
return tar.ConvertToString().Replace(deletechar.ToString(CultureInfo.InvariantCulture), string.Empty);
}
Sample
var input = "rumbaton jonathan \"racko\" contreras";
var cleaned = input.Delete("\"\\/*?><|");
Will result in:
rumbaton jonathan racko contreras
Ok ! I've solved my issue thanks to all your indications. This is my correction :
string newFileName = _artist + " - " + _title;
char[] invalidFileChars = Path.GetInvalidFileNameChars();
char[] invalidPathChars = Path.GetInvalidPathChars();
foreach (char invalidChar in invalidFileChars)
{
newFileName = newFileName.Replace(invalidChar.ToString(), string.Empty);
}
foreach (char invalidChar in invalidPathChars)
{
newFilePath = newFilePath.Replace(invalidChar.ToString(), string.Empty);
}
Thank you so musch everybody :)
i have a string Like
"Hello i want to go."
my code give "want to go."
but i need string between " i " and " to " how can i get this? my code is as below.
string[] words = Regex.Split("Hello i want to go.", " i ");
string respons = words[1];
string input = "Hello i want to go.";
Regex regex = new Regex(#".*\s[Ii]{1}\s(\w*)\sto\s.*");
Match match = regex.Match(input);
string result = string.Empty;
if (match.Success)
{
result = match.Groups[1].Value;
}
This regex will match any 'word' between 'i' (not case sensitive) and 'to'.
EDIT: changed ...to.* => to\s.* as suggested in the comments.
string input = "Hello I want to go.";
string result = input.Split(" ")[2];
If you want the word after the "i" then:
string result = input.Split(" i ")[1].Split(" ")[0];
Use
string s = "Hello i want to go.";
string[] words = s.split(' ');
string response = wor
just do it with one simple line of code
var word = "Hello i want to go.".Split(' ')[2];
//Returns the word "want"
string input = "Hello I want to go.";
string[] sentenceArray = input.Split(' ');
string required = sentenceArray[2];
Here's an example using Regex which gives you the index of each occurrence of "want":
string str = "Hello i want to go. Hello i want to go. Hello i want to go.";
Match match = Regex.Match(str, "want");
while(match.Success){
Console.WriteLine(string.Format("Index: {0}", match.Index));
match = match.NextMatch();
}
Nowhere does it say Regex...
string result = input.Split.Skip(2).Take(1).First()
it's work
public static string Between(this string src, string findfrom, string findto)
{
int start = src.IndexOf(findfrom);
int to = src.IndexOf(findto, start + findfrom.Length);
if (start < 0 || to < 0) return "";
string s = src.Substring(
start + findfrom.Length,
to - start - findfrom.Length);
return s;
}
and it can be called as
string respons = Between("Hello i want to go."," i "," to ");
it return want
I am wondering what would be the best way to specify an array of characters like,
{
}
[
]
and then check a string for these and if they are there, to completely remove them.
if (compiler.Parser.GetErrors().Count == 0)
{
AstNode root = compiler.Parse(phrase.ToLower());
if (compiler.Parser.GetErrors().Count == 0)
{
try
{
fTextSearch = SearchGrammar.ConvertQuery(root, SearchGrammar.TermType.Inflectional);
}
catch
{
fTextSearch = phrase;
}
}
else
{
fTextSearch = phrase;
}
}
else
{
fTextSearch = phrase;
}
string[] brackets = brackets = new string[]
{
"{",
"}",
"[",
"]"
};
string[] errorChars = errorChars = new string[]
{
"'",
"&"
};
StringBuilder sb = new StringBuilder();
string[] splitString = fTextSearch.Split(errorChars, StringSplitOptions.None);
int numNewCharactersAdded = 0;
foreach (string itm in splitString)
{
sb.Append(itm); //append string
if (fTextSearch.Length > (sb.Length - numNewCharactersAdded))
{
sb.Append(fTextSearch[sb.Length - numNewCharactersAdded]); //append splitting character
sb.Append(fTextSearch[sb.Length - numNewCharactersAdded - 1]); //append it again
numNewCharactersAdded++;
}
}
string newString = sb.ToString();
A regular expression can do this far more easily:
var result = Regex.Replace(input, #"[[\]()]", "");
Using a character set ([...]) to match anyone of the characters in it and replace with nothing. Regex.Replace will replace all matches.
Another concise way is using Enumerable.Except to get the set difference of the Chars(assuming brackets are chars):
String newString = new String(oldString.Except(brackets).ToArray());
string str = "faslkjnro(fjrmn){ferqwe}{{";
char[] separators = new []{'[', ']','{','}' };
var sb = new StringBuilder();
foreach (var c in str)
{
if (!separators.Contains(c))
{
sb.Append(c);
}
}
return sb.ToString();
How about this:
string myString = "a12{drr[ferr]vgb}rtg";
myString = myString.Replace("[", "").Replace("{", "").Replace("]", "").Replace("}", "");
You end up with:
a12drrferrvgbrtg
I don't know if I understand your problem, but you can solve your problem with this:
string toRemove = "{}[]";
string result = your_string_to_be_searched;
foreach(char c in toRemove)
result = result.Replace(c.ToString(), "");
or with an extension method
static class Extensions
{
public static string RemoveAll(this string src, string chars)
{
foreach(char c in chars)
src= src.Replace(c.ToString(), "");
return src;
}
}
With this you can use string result = your_string_to_be_searched.RemoveAll("{}[]");
string charsToRemove = #"[]{}";
string pattern = string.Format("[{0}]", Regex.Escape(charsToRemove));
var result = Regex.Replace(input, pattern, "");
The primary advantage of this over some of the other similar answers is that you aren't bothered with determining which characters need to be escaped in RegEx; you can let the library take care of that for you.
You can do this in a pretty compact fashion like this:
string s = "ab{c[d]}";
char[] ca = new char[] {'{', '}', '[', ']'};
Array.ForEach(ca, e => s = s.Replace(e.ToString(), ""));
Or this:
StringBuilder s = new StringBuilder("ab{c[d]}");
char[] ca = new char[] {'{', '}', '[', ']'};
Array.ForEach(ca, e => s.Replace(e.ToString(), ""));
Taken from this answer: https://stackoverflow.com/a/12800424/1498669
Just use .Split() with the char[] of your desired removeables and recapture it with .Join() or .Concat()
char[] delChars = "[]{}<>()".ToCharArray();
string input = "some (crazy) string with brac[et]s in{si}de";
string output = string.Join(string.Empty, input.Split(delChars));
//or
string output = string.Concat(input.Split(delChars));
References:
https://learn.microsoft.com/en-us/dotnet/csharp/how-to/parse-strings-using-split
https://learn.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings#code-try-4