Remove characters from a specific index character - c#

I would like to know how can i remove characters in a string from a specific index like :
string str = "this/is/an/example"
I want to remove all characters from the third '/' including so it would be like this:
str = "this/is/an"
I tried with substring and regex but i cant find a solution.

Using string operations:
str = str.Substring(0, str.IndexOf('/', str.IndexOf('/', str.IndexOf('/') + 1) + 1));
Using regex:
str = Regex.Replace(str, #"^(([^/]*/){2}[^/]*)/.*$", "$1");

To get "this/is/an":
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/'));
If you need to keep the slash:
string str = "this/is/an/example";
string new_string = str.Remove(str.LastIndexOf('/')+1);
This expects there to be at least one slash. If none are present, you should check it beforehand to not throw an exception:
string str = "this.s.an.example";
string newStr = str;
if (str.Contains('/'))
newStr = str.Remove(str.LastIndexOf('/'));
If its importaint to get the third one, make a dynamic method for it, like this. Input the string, and which "folder" you want returned. 3 in your example will return "this/is/an":
static string ReturnNdir(string sDir, int n)
{
while (sDir.Count(s => s == '/') > n - 1)
sDir = sDir.Remove(sDir.LastIndexOf('/'));
return sDir;
}

This regex is the answer: ^[^/]*\/[^/]*\/[^/]*. It will capture the first three chunks.
var regex = new Regex("^[^/]*\\/[^/]*\\/[^/]*", RegexOptions.Compiled);
var value = regex.Match(str).Value;

I think the best way of doing that it's creating a extension
string str = "this/is/an/example";
str = str.RemoveLastWord();
//specifying a character
string str2 = "this.is.an.example";
str2 = str2.RemoveLastWord(".");
With this static class:
public static class StringExtension
{
public static string RemoveLastWord(this string value, string separator = "")
{
if (string.IsNullOrWhiteSpace(value))
return string.Empty;
if (string.IsNullOrWhiteSpace(separator))
separator = "/";
var words = value.Split(Char.Parse(separator));
if (words.Length == 1)
return value;
value = string.Join(separator, words.Take(words.Length - 1));
return value;
}
}

Related

Get the part of a string before new line symbol

I do want to get all the text before the first \r\n\ symbol. For example,
lalal lalal laldlasdaa daslda\r\n\Prefersaasda reanreainrea
I would need: lalal lalal laldlasdaa daslda. The above string can be empty, but it also may not contain any '\r\n\' symbol." How can I achieve this?
You can use IndexOf to get the position, then use Substring to get the first part:
string s = "lalal lalal laldlasdaa daslda\r\n Prefersaasda reanreainrea";
int positionOfNewLine = s.IndexOf("\r\n");
if (positionOfNewLine >= 0)
{
string partBefore = s.Substring(0, positionOfNewLine);
}
Hope that this is what you are looking for:
string inputStr = "lalal lalal laldlasdaa daslda\r\nPrefersaasda reanreainrea";
int newLineIndex = inputStr.IndexOf("\r\n");
if(newLineIndex != -1)
{
string outPutStr = inputStr.Substring(0, newLineIndex );
// Continue
}
else
{
// Display message no new line character
}
Checkout an example here
You can use Split like this
string mystring = #"lalal lalal laldlasdaa daslda\r\n\Prefersaasda reanreainrea";
string mylines = mystring.Split(new string[] { #"\r\n" }, StringSplitOptions.None)[0];
Whereas if the string is like
string mystring = "lalal lalal laldlasdaa daslda\r\n Prefersaasda reanreainrea";
string mylines = mystring.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)[0];
Environment.NewLine will also work with it. The with \r\n\P is making that string an invalid string thus \r\n P makes it a new line

String replace in specific positioned in c#

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"]);

How do I delete the values in between the tags?

I want to delete the values inside the tags, how can I do that? the highlighted output is what I want to delete when I load the save the file.
<data name="Enrolment_Exit_Verify_Message" d2p1:space="preserve" xmlns:d2p1="http://www.w3.org/XML/1998/namespace">
<value**>**Are you sure you want to Exit without Saving?****</value>
<comment>[Font]**Italic**[/Font][DateStamp]2015/02/01 00:00:00[/DateStamp][Comment] **this is a My awesome new comments comment.!!**[/Comment]</comment>
Here is how I have read in between the tags? I don't know how can I delete in-between the tags.
for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
{
string comment = oDataSet.Tables["data"].Rows[i][2].ToString();
string font = Between(comment, "[Font]", "[/Font]");
string datestamp = Between(comment, "[DateStamp]", "[/DateStamp]");
string commentVal = Between(comment, "[Comment]", "[/Comment]");
string[] row = new string[]
{
oDataSet.Tables["data"].Rows[i][0].ToString(),
oDataSet.Tables["data"].Rows[i][1].ToString(),
font,
datestamp, commentVal };
Gridview_Output.Rows.Add(row);
}
oDataSet.Tables.Add(oDataTable);
string function
public string Between(string STR, string FirstString, string LastString)
{
string FinalString;
int Pos1 = STR.IndexOf(FirstString) + FirstString.Length;
int Pos2 = STR.IndexOf(LastString);
FinalString = STR.Substring(Pos1, Pos2 - Pos1);
return FinalString;
}
You can go with the regex in your between method if you can build up the regex. Here is more info on the regex
public string Between(string STR, string FirstString, string LastString)
{
string regularExpressionPattern1 = #"(?:\" + FirstString + #")([^[]+)\[\/" + LastString;
Regex regex = new Regex(regularExpressionPattern1, RegexOptions.Singleline);
MatchCollection collection = regex.Matches(STR.ToString());
var val = string.Empty;
foreach (Match m in collection)
{
val = m.Groups[1].Value;
}
return val;
}
Note- Code is not tested may need to tweak for your need . Althoguh regex expression is tested.
Here is working fiddle for regex
The above code give you the values from the tags in you r case after executing the functions the variables will have the values
font = "**Italic**"
datestamp = "2015/02/01 00:00:00"
commentVal = "**this is a My awesome new comments comment.!!**"
Then if you want it to remove from the comment variable just use Replaceas
comment = comment.Replace(font,string.Empty);
comment = comment.Replace(datestamp ,string.Empty);
comment = comment.Replace(commentVal ,string.Empty);
At the end of it you will have the comment variable with removed values from that tags.
To delete the values in between you can modify the regular expression provided by #Coder of Code as shown below:
string str = "[Font]**Italic**[/Font][DateStamp]2015/02/01 00:00:00[/DateStamp][Comment] **this is a My awesome new comments comment.!!**[/Comment]";
string strPattern = #"(?:])([^[]+)\["; // Regular expression pattern to find string inside ][
Regex rg = new Regex(strPattern);
string newStr = rg.Replace(str, string.Format("]{0}[",string.Empty), int.MaxValue);

How to trim/replace a char '\' or '"' from a string?

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 :)

Retrieving string from a string which is in between two String?

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

Categories

Resources