I have this string, I want to get the part after the date. The part till date always remains the same. I would have hoped to get the index of date but it changes always hence I can't use it.
var str = "c:\ somefolder\ download\ 2019-14-11 merchandise of today"
char[] spearator = {" "};
var _split = str.Split(spearator);
Here I have all the words broken down according to spaces.
How do I get the 'merchandise of today'?
You can try following codes, use the regular expression
var str = #"c:\ somefolder\ download\ 2019-14-11 merchandise of today";
var reg = new Regex(#".+\d{4}-\d{2}-\d{2}");
var result = reg.Replace(str, string.Empty).Trim();
If the format of the date does not change, you could do the following:
var path = #"C:\Example\Download\2019-14-11 Merchandise Of Today";
var merchandise = path.Substring(path.LastIndexOf('\\')).Trim();
OR
var merchandiseWithoutDate = path.Substring(path.IndexOf(' ').Trim();
That will output the date and merchandise of today, if you change the character to a space you will also retrieve that.
What Substring is basically allows you to control an index to begin and end, which allows you to mitigate the text received.
//Thanks guys!
//This is what I did before I saw the two answers. I know it is messy a lot and now I am //gonna try the substring method but this was a temporary fix for me. Thanks again!
var str = "c:\ somefolder\ download\ 2019-14-11 merchandise of today"
char[] spearator = {" "};
var _split = str.Split(spearator);
int len = _split.lenght-1;
for(i=0; i<_split.lenght; i++)
{
var getStr = _split[i]
Match search = regex.match(getStr, "my regex patern for date");
if (search.success)
{
var converted = search.tostring();
int index = Array.IndexOf(_split, converted)
index++;
string temp = "";
while(index<=len_)
{
string temp = temp+ " "+_split[index];
index++;
}
console.writeline("String is {0}", temp);
}
}
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 new with C# and in and I have some questions.
I'm writing some program that get the following output from remote machine (using SSH):
wwn = 5001248018b6d7af
node_wwn = 5001248018b6d7ae
wwn = 5001248118b6d7af
node_wwn = 5001248118b6d7ae
wwn = 5001248218b6d7af
node_wwn = 5001248218b6d7ae
wwn = 5001248318b6d7af
node_wwn = 5001248318b6d7ae
The output above save into string...
I need to extract from this output List or Array in the following format:
50:01:24:80:18:b6:d7:af:50:01:24:80:18:b6:d7:ae
each two lines are couple (wwn and node_wwn)
I worth the following function
public void OutPutParse (string output)
{
string wwnn = null;
string wwpn = null;
string[] test = output.Split('\n');
test = test.Where(item => !string.IsNullOrEmpty(item)).ToArray();
//run all over the test array and exrract the wwns and wwpn
for (int i = 0; i < test.Length; i++)
{
}
}
this function create an array (test) of wwns and node_wwn
the expected results is an array or list the will include wwn + node_wwn like this
50:01:24:80:18:b6:d7:af:50:01:24:80:18:b6:d7:ae
The easiest way to achieve this is:
string www = "5001248018b6d7af";
string wwwn = "5001248018b6d7ae";
string myString = "";
// Implemenet loop here.
// www = "number" // the next number you get
// wwwn = "number" // the next number you get
myString = www + myString + wwwn;
You just have to do it with a loop when you have a list of strings or something.
If you want to have it in the same order you can either do it with a character between the strings like a ";" and split all numbers or you just do two strings and combine them at the end like that:
string www = "5001248018b6d7af";
string wwwn = "5001248018b6d7ae";
string mywwwString = "";
string mywwwnString = "";
// Implement the loop to add strings here
// www = "number" // the next number you get
// wwwn = "number" // the next number you get
mywwwString += www;
mywwwnString += wwwn;
string myString = www + wwwn;
I have a string Classic-T50 (Black+Grey)
when i send to by query string it will show in next page
Classic-T50 (Black Grey)
so i want to add + in space in this string only within bracket() only portion.
Classic-T50 (Black+Grey).
I have tried string.Replace(" ","+").But it produce
Classic-T50+(Black+Grey).
But i want string Classic-T50 (Black+Grey).
Help me please.
You can use a regular expression for replacing all spaces inside brackets:
var pattern = #"\s(?![^)]*\()";
var data = "Classic-T50 (Black Grey)";
var replacement = "+";
var regex = new Regex(pattern);
var transformedData = regex.Replace(data, replacement); // Classic-T50 (Black+Grey)
This approach will work for any input string. E.g., the string Caption ( A B C D ) will transform to Caption (+A+B+C+D+).
Additional links:
Regex explanation: https://regex101.com/r/aN8fV2/1
MSDN: Regex.Replace Method (String, String)
What is the format of the strings that you want to modify? Will this code work?
void Main()
{
var str = "Classic-T50 (Black Grey)";
Console.WriteLine(FormatWithPlus(str));
}
public string FormatWithPlus(string str){
var str1 = str.Substring(0, str.IndexOf('('));
var str2 = str.Substring(str.IndexOf('('));
return str1 + str2.Replace(' ', '+');
}
Use a StringBuilder and convert back to string. StringBuilder's differ from strings in that they're mutable and noninterned. It stores data in an array, and so you can replace characters like you would in an array:
void Main()
{
var input = "Classic-T50 (Black Grey)";
StringBuilder inputsb = new StringBuilder(input);
var openParens = input.IndexOf('(');
var closeParens = input.IndexOf(')');
var count = closeParens - openParens;
//Console.WriteLine(input);
//inputsb[18] = '+';
inputsb.Replace(' ', '+', openParens, count);
Console.WriteLine(inputsb.ToString());
}
See StringBuilder.Replace Method (Char, Char, Int32, Int32
try:
String.Replace("k ","k+")
use this code
public class Program
{
private static void Main(string[] args)
{
const string abc = "Classic-T50 (Black Grey)";
var a = abc.Replace("k ", "k+");
Console.WriteLine(a);
Console.ReadKey();
}
}
You can UrlEncode it to preserve the special character:
Server.UrlEncode(mystring)
Or replace + sign with "%252b" and then encode it:
string myTitle = mystring.Trim().Replace("+", "%252b");
Response.Redirect("~/default.aspx?title=" + Server.UrlEncode(myTitle));
Remember to decode it once you try to retrieve it :
Server.UrlDecode(Request.QueryString["title"]);
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