So as the title says I want to know how to remove text after point in a string. E.g.
I have a string, "abcdefg#fedcba". How can I remove any text that is after the # symbol (if we did not know what was after it)?
string input = "abcdefg#fedcba";
string result = input.Substring(0, input.IndexOf('#'));
To make solution more flexible you can use a variable:
char borderCharacter = '#';
string input = '...';
string result = input.Substring(0, input.IndexOf(borderCharacter));
Related
Im am very new in C#.
How i can delete first element of a string using a method,i find something on this site but didnt work so help me please.
For example
string newString = oldString.Substring(1);
If you want to remove the first word from your string you could use LINQ Skip combined with String.Split and String.Join:
string str = "How are you?";
string result = string.Join(" ", str.Split().Skip(1));//"are you?"
If you want only to remove the first letter you could use String.Substring:
string result = str.Substring(1);//"ow are you?";
Or if you want a LINQ solution you could use LINQ Skip:
string result = new string(str.Skip(1).ToArray());//"ow are you?";
Another solution is to use Remove method:
string myStr = "dsafavveebvesf";
//remove one character at position 0 - at the beginning
myStr = myStr.Remove(0, 1);
If you are not aware of Linq, you can simply use for loop to do the same.
Here you can use Split method of string.
string amit = "my name is amit";
string restultStr = string.Empty;
//taking all words in sentence in one array
string [] strWords = amit.Split();
//as we start this with 1 instead of 0, it will ignore first word
for (int i = 1; i < strWords.Length; i++)
{
restultStr += strWords[i] + " ";
}
EDIT
Now I see there are two onions here, removing first letter of the string and removing first word.
Above answer was to remove first word. if you want to just remove first letter, you can always do as suggested.
string amit = "my name is amit";
string restultStr = amit.Substring(1);
In the below code i have a string array which holds values like "1,2,3" i want to remove the double quotes and display as 1,2,3.pls help me to do this.
string[] Stocks = StockDetails.ToArray();
string s = string.Join(",", Stocks);
You can just use string.Replace
var listOfStrings = StockDetails.Select(s => s.Replace("\"", string.Empty))
.ToList();
If you're having string in this format
string str = "\"1,2,3\"";
..then you can simply remove the double quotation marks using Replace method on string.
str = str.Replace("\"", "");
..this will replace the double quotation from your string, and will return the simple text that is not a double quotes.
More I don't think strings are like this, you're having a look at the actual value of the variable string you're having. When you will use it, it will give you the actual 1, 2, 3 but however, use the above code to remove the quotation .
I have a string in a masked TextBox that looks like this:
123.456.789.abc.def.ghi
"---.---.---.---.---.---" (masked TextBox format when empty, cannot use underscore X( )
Please ignore the value of the characters (they can be duplicated, and not unique as above). How can I pick out part of the string, say "789"? String.Remove() does not work, as it removes everything after the index.
You could use Split in order to separate your values if the . is always contained in your string.
string input = "123.456.789.abc.def";
string[] mySplitString = input.Split('.');
for (int i = 0; i < mySplitString.Length; i++)
{
// Do you search part here
}
Do you mean you want to obtain that part of the string? If so, you could use string.Split
string s = "123.456.789.abc.def.ghi";
var splitString = s.Split('.');
// splitString[2] will return "789"
You could simply use String.Split (if the string is actually what you have shown)
string str = "123.456.789.abc.def.ghi";
string[] parts = str.Split('.');
string third = parts.ElementAtOrDefault(2); // zero based index
if(third != null)
Console.Write(third);
I've just used Enumerable.ElementAtOrDefault because it returns null instead of an exception if there's no such index in the collection(It falls back to parts[2]).
Finding a string:
string str="123.456.789.abc.def.ghi";
int i = str.IndexOf("789");
string subStr = str.Substring(i,3);
Replacing the substring:
str = str.Replace("789","").Replace("..",".");
Regex:
str = Regex.Replace(str,"789","");
The regex can give you a lot of flexibility finding things with minimum code, the drawback is it may be difficult to write them
If you know the index of where your substring begins and the length that it will be, you can use String.Substring(). This will give you the substring:
String myString = "123.456.789";
// looking for "789", which starts at index 8 and is length 3
String smallString = myString.Substring(8, 3);
If you are trying to remove a specific part of the string, use String.Replace():
String myString = "123.456.789";
String smallString = myString.Replace("789", "");
var newstr = new String(str.where(c => "789")).tostring();..i guess this would work or you can use sumthng like this
Try using Replace.
String.Replace("789", "")
I have a data file in INI file like format that needs to be read by both some C code and some C# code. The C code expects string values to be surrounded in quotes. The C# equivalent code is using some underlying class or something I have no control over, but basically it includes the quotes as part of the output string. I.e. data file contents of
MY_VAL="Hello World!"
gives me
"Hello World!"
in my C# string, when I really need it to contain
Hello World!
How do I conditionally (on having first and last character being a ") remove the quotes and get the string contents that I want.
On your string use Trim with the " as char:
.Trim('"')
I usually call String.Trim() for that purpose:
string source = "\"Hello World!\"";
string unquoted = source.Trim('"');
My implementation сheck that quotes are from both sides
public string UnquoteString(string str)
{
if (String.IsNullOrEmpty(str))
return str;
int length = str.Length;
if (length > 1 && str[0] == '\"' && str[length - 1] == '\"')
str = str.Substring(1, length - 2);
return str;
}
Just take the returned string and do a Trim('"');
Being obsessive, here (that's me; no comment about you), you may want to consider
.Trim(' ').Trim('"').Trim(' ')
so that any, bounding spaces outside of the quoted string are trimmed, then the quotation marks are stripped and, finally, any, bounding spaces for the contained string are removed.
If you want to retain contained, bounding white space, omit the final .Trim(' ').
Should there be embedded spaces and/or quotation marks, they will be preserved. Chances are, such are desired and should not be deleted.
Do some study as to what a no argument Trim() does to things like form feed and/or tabulation characters, bounding and embedded. It could be that one and/or the other Trim(' ') should be just Trim().
If you know there will always be " at the end and beginning, this would be the fastest way.
s = s.Substring(1, s.Length - 2);
Use string replace function or trim function.
If you just want to remove first and last quotes use substring function.
string myworld = "\"Hello World!\"";
string start = myworld.Substring(1, (myworld.Length - 2));
I would suggest using the replace() method.
string str = "\"HelloWorld\"";
string result = str.replace("\"", string.Empty);
What you are trying to do is often called "stripping" or "unquoting". Usually, when the value is quoted that means not only that it is surrounded by quotation characters (like " in this case) but also that it may or may not contain special characters to include quotation character itself inside quoted text.
In short, you should consider using something like:
string s = #"""Hey ""Mikey""!";
s = s.Trim('"').Replace(#"""""", #"""");
Or when using apostrophe mark:
string s = #"'Hey ''Mikey''!";
s = s.Trim('\'').Replace("''", #"'");
Also, sometimes values that don't need quotation at all (i.e. contains no whitespace) may not need to be quoted anyway. That's the reason checking for quotation characters before trimming is reasonable.
Consider creating a helper function that will do this job in a preferable way as in the example below.
public static string StripQuotes(string text, char quote, string unescape)a
{
string with = quote.ToString();
if (quote != '\0')
{
// check if text contains quote character at all
if (text.Length >= 2 && text.StartsWith(with) && text.EndsWith(with))
{
text = text.Trim(quote);
}
}
if (!string.IsNullOrEmpty(unescape))
{
text = text.Replace(unescape, with);
}
return text;
}
using System;
public class Program
{
public static void Main()
{
string text = #"""Hello World!""";
Console.WriteLine(text);
// That will do the job
// Output: Hello World!
string strippedText = text.Trim('"');
Console.WriteLine(strippedText);
string escapedText = #"""My name is \""Bond\"".""";
Console.WriteLine(escapedText);
// That will *NOT* do the job to good
// Output: My name is \"Bond\".
string strippedEscapedText = escapedText.Trim('"');
Console.WriteLine(strippedEscapedText);
// Allow to use \" inside quoted text
// Output: My name is "Bond".
string strippedEscapedText2 = escapedText.Trim('"').Replace(#"\""", #"""");
Console.WriteLine(strippedEscapedText2);
// Create a function that will check texts for having or not
// having citation marks and unescapes text if needed.
string t1 = #"""My name is \""Bond\"".""";
// Output: "My name is \"Bond\"."
Console.WriteLine(t1);
// Output: My name is "Bond".
Console.WriteLine(StripQuotes(t1, '"', #"\"""));
string t2 = #"""My name is """"Bond"""".""";
// Output: "My name is ""Bond""."
Console.WriteLine(t2);
// Output: My name is "Bond".
Console.WriteLine(StripQuotes(t2, '"', #""""""));
}
}
https://dotnetfiddle.net/TMLWHO
Here's my solution as extension method:
public static class StringExtensions
{
public static string UnquoteString(this string inputString) => inputString.TrimStart('"').TrimEnd('"');
}
It's just trimming at the start an the end...
i have a username= LICTowner.
i need to get the prefix from the word LICTowner i.e LICT.
how to split the word and get the 4 letter prefix.
in asp.net using C#
if the prefix is ALWAYS 4 letters you can use the Substring method:
var prefix = username.Substring(0, 4);
where the first int is the start index and the second int is the length.
Substring on MSDN
String userName = "LICTowner";
String prefix = userName.Substring(0,4); // LICT
String restOfWord = userName.Substring(4); // owner
hmmmm.... before anything, a) you should really look for similar questions and b) thats not a hard problem to do... i mean, have you even tried???
if the prefix is always 4 letters, then just use the .Substring method... as in
string username;
string prefix=username.Substring(0,4)// or something like that, cant remember off the top of my head
string s = "LICTowner";
Label1.Text= Regex.Replace(s, "[^A-Z]", "");
Simple regular expression to remove all characters other than upper case
string name="aryan";
string prefixwords= name.substring(a,b);
//a from where you want the string
// b till where you need the string now take any label and print the value
string prefixwords= name.substring(0,2);
label lblmsg= new label();
lblmsg=prefixwords.tostring(); // ary
string restofwords= name.substring(2); // an
If the prefix is always 4 characters use simple substring
Else
a) remove all non upper case characters
string s = "LICTowner";
Label1.Text= Regex.Replace(s, "[^A-Z]", "");
b)
split at the first non upper case character
Label1.Text= Regex.Split(s, "[^A-Z]")[0];
You can use the Substring() function to get the first four Character.
string mystring = "LISTowner";
string prefixword = mystring.Substring(0,4);
Label label1 = new Label();
label1.Text = prefixword;