TrimEnd() not working - c#

I want to trim the end off a string if it ends in ", ". That's a comma and a space.
I've tried TrimEnd(', '), but this doesn't work. It has to be only if the string ends this way, so I can't just use .Remove to remove the last two characters. How can I do it?

string txt = " testing, , ";
txt = txt.TrimEnd(',',' '); // txt = "testing"
This uses the overload TrimEnd(params char[] trimChars). You can specify 1 or more chars that will form the set of chars to remove. In this case comma and space.

This should work:
string s = "Bar, ";
if (s.EndsWith(", "))
s = s.Substring(0, s.Length - 2);
EDIT
Come to think of it, this would make a nice extension method:
public static String RemoveSuffix(this string value, string suffix)
{
if (value.EndsWith(suffix))
return value.Substring(0, value.Length - suffix.Length);
return value;
}

Try this:
string someText = "some text, ";
char[] charsToTrim = { ',', ' ' };
someText = someText.TrimEnd(charsToTrim);
Works for me.

The catch is that mystring.Trim(',') will only work if you reassign it to the string itself like this:
mystring = mystring.Trim(',')

"value, ".Trim().TrimEnd(",") should also work.

if (model != null && ModelState.IsValid)
{
var categoryCreate = new Categories
{
CategoryName = model.CategoryName.TrimStart().TrimEnd(),
Description = model.Description.TrimStart().TrimEnd()
};
_CategoriesService.Create(categoryCreate);
}
TrimStart().TrimEnd() == Left Trim and Right Trim

Related

Replace all Special Characters including space with - using C#

I want to replace all Special Characters which can't be parse in URL including space, double space or any big space with '-' using C#.
I don't want to use any Parse Method like System.Web.HttpUtility.UrlEncode.
How to do this ? I want to include any number of space between two words with just one '-'.
For example, if string is Hello# , how are you?
Then, Result should be, Hello-how-are-you, no '-' if last index is any special character or space.
string str = "Hello# , how are you?";
string newstr = "";
//Checks for last character is special charact
var regexItem = new Regex("[^a-zA-Z0-9_.]+");
//remove last character if its special
if (regexItem.IsMatch(str[str.Length - 1].ToString()))
{
newstr = str.Remove(str.Length - 1);
}
string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");
INPUT:
Hello# , how are you?
OUTPUT:
Hello-how-are-you
EDIT:
Wrap it inside a class
public static class StringCheck
{
public static string Checker()
{
string str = "Hello# , how are you?";
string newstr = null;
var regexItem = new Regex("[^a-zA-Z0-9_.]+");
if (regexItem.IsMatch(str[str.Length - 1].ToString()))
{
newstr = str.Remove(str.Length - 1);
}
string replacestr = Regex.Replace(newstr, "[^a-zA-Z0-9_]+", "-");
return replacestr;
}
}
and call like this,
string Result = StringCheck.Checker();
string[] arr1 = new string[] { " ", "#", "&" };
newString = oldString;
foreach repl in arr1
{
newString= newString.Replace(repl, "-");
}
Of course you can add into an array all of your spec characters, and looping trough that, not only the " ".
More about the replace method at the following link
You need two steps to remove last special character and to replace all the remaining one or more special characters with _
public static void Main()
{
string str = "Hello# , how are you?";
string remove = Regex.Replace(str, #"[\W_]$", "");
string result = Regex.Replace(remove, #"[\W_]+", "-");
Console.WriteLine(result);
Console.ReadLine();
}
IDEONE

Trim a string in c# after special character

I want to trim a string after a special character..
Lets say the string is str="arjunmenon.uking". I want to get the characters after the . and ignore the rest. I.e the resultant string must be restr="uking".
How about:
string foo = str.EverythingAfter('.');
using:
public static string EverythingAfter(this string value, char c)
{
if(string.IsNullOrEmpty(value)) return value;
int idx = value.IndexOf(c);
return idx < 0 ? "" : value.Substring(idx + 1);
}
you can use like
string input = "arjunmenon.uking";
int index = input.LastIndexOf(".");
input = input.Substring(index+1, input.Split('.')[1].ToString().Length );
Use Split function
Try this
string[] restr = str.Split('.');
//restr[0] contains arjunmenon
//restr[1] contains uking
char special = '.';
var restr = str.Substring(str.IndexOf(special) + 1).Trim();
Try Regular Expression Language
using System.IO;
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "arjunmenon.uking";
string pattern = #"[a-zA-Z0-9].*\.([a-zA-Z0-9].*)";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(match.Value);
if (match.Groups.Count > 1)
for (int ctr = 1; ctr < match.Groups.Count; ctr++)
Console.WriteLine(" Group {0}: {1}", ctr, match.Groups[ctr].Value);
}
}
}
Result:
arjunmenon.uking
Group 1: uking
Personally, I won't do the split and go for the index[1] in the resulting array, if you already know that your correct stuff is in index[1] in the splitted string, then why don't you just declare a constant with the value you wanted to "extract"?
After you make a Split, just get the last item in the array.
string separator = ".";
string text = "my.string.is.evil";
string[] parts = text.Split(separator);
string restr = parts[parts.length - 1];
The variable restr will be = "evil"
string str = "arjunmenon.uking";
string[] splitStr = str.Split('.');
string restr = splitStr[1];
Not like the methods that uses indexes, this one will allow you not to use the empty string verifications, and the presence of your special caracter, and will not raise exceptions when having empty strings or string that doesn't contain the special caracter:
string str = "arjunmenon.uking";
string restr = str.Split('.').Last();
You may find all the info you need here : http://msdn.microsoft.com/fr-fr/library/b873y76a(v=vs.110).aspx
cheers
I think the simplest way will be this:
string restr, str = "arjunmenon.uking";
restr = str.Substring(str.LastIndexOf('.') + 1);

C# split string of first character occurrence

I thought this was simple but this is just kicking my butt.
I have this string 21. A.Person I simply want to get A.Person out of this.
I try the following but I only get 21
string[] pName = values[i, j].ToString().Split(new char[] { '.' }, 2);
pName[1] ???
values[i, j].ToString() = 21. A.Person and yes I've verified this.
Try this:
var substr="";
var indedx = yourString.IndexOf('.');
if(index>-1)
substr = yourString.Substring(index);
substr=substr.Trim();
For string "21. A.Person" should return "A.Person"
Everyone is giving you alternate solutions when yours should work.
The problem is that values[i, j] must not equal 21. A.Person
I plugged it into a simple test..
[Test]
public void junk()
{
string[] pName = "21. A.Person".Split(new char[] { '.' }, 2);
Console.WriteLine(pName[1]);
}
What does it print?
A.Person
(With the space in the front, because you didn't trim the space)
I would use substring() with the position of the first '.' as your start point:
var name = sourceString.Substring(sourceString.IndexOf('.'));
string pName = values[i, j].ToString().Substring(values[i, j].ToString().IndexOf('.')+1);
Try something like that:
var str = "21. A.Person";
var index = str.IndexOf('.') +1;
var substr = str.Substring(index, str.Length - index);

How to concatenate a string with blankspaces?

I need to create a 10-character string. If the string has less than 10 characters i need to append blank spaces till complete the entire 10-character string. I do the following but I have no succes, the result string has only one blank space concateneted in the end:
public void MyMethod(string[] mystrings)
{
mystring[i].PadRight(10- mystrings[i].length)
// Here I need a 10 char string. For example:
// "1234567 "
}
Thank you.
You could use String.PadRight:
mystring = mystring.PadRight(10, ' ');
(You can omit the second parameter, as in your case, when you use spaces).
Note however, that if mystring is already longer than 10 characters, it will remain longer. It is not clear from your question, if you need a string with exactly 10 characters length. If so, then do something like:
mystring = mystring.PadRight(10).Substring(0, 10);
You can use string.Format with a custom format string:
mystring = string.Format("{0,-10}", mystring);
You need to use the string.PadRight method:
string result = mystring.PadRight(10);
try this
string str = "cc";
int charstoinsert = 10 - str.Length;
for (int i = 0; i < charstoinsert; i++)
{
str += " ";
}
Try with following function
#region GetPaddedString
private string GetPaddedString(string strValue, int intLength)
{
string strReturn = string.Empty;
string _strEmptySpace = " ";
int _vinLength = strValue.Length;
if (_vinLength < intLength)
{
strReturn = strValue + _strEmptySpace.PadRight((intLength - _vinLength));
}
else
{
strReturn = strValue;
}
return strReturn;
}
#endregion
GetPaddedString("test", 10)
This should do the trick:
str.PadRight(10, ' ').Substring(0, 10)
try this
string mystring= "sd";
while (mystring.Length <= 10)
{
mystring+= " ";
}

How to make a first letter capital in C#

How can the first letter in a text be set to capital?
Example:
it is a text. = It is a text.
public static string ToUpperFirstLetter(this string source)
{
if (string.IsNullOrEmpty(source))
return string.Empty;
// convert to char array of the string
char[] letters = source.ToCharArray();
// upper case the first char
letters[0] = char.ToUpper(letters[0]);
// return the array made of the new char array
return new string(letters);
}
It'll be something like this:
// precondition: before must not be an empty string
String after = before.Substring(0, 1).ToUpper() + before.Substring(1);
polygenelubricants' answer is fine for most cases, but you potentially need to think about cultural issues. Do you want this capitalized in a culture-invariant way, in the current culture, or a specific culture? It can make a big difference in Turkey, for example. So you may want to consider:
CultureInfo culture = ...;
text = char.ToUpper(text[0], culture) + text.Substring(1);
or if you prefer methods on String:
CultureInfo culture = ...;
text = text.Substring(0, 1).ToUpper(culture) + text.Substring(1);
where culture might be CultureInfo.InvariantCulture, or the current culture etc.
For more on this problem, see the Turkey Test.
If you are using C# then try this code:
Microsoft.VisualBasic.StrConv(sourceString, Microsoft.VisualBasic.vbProperCase)
I use this variant:
private string FirstLetterCapital(string str)
{
return Char.ToUpper(str[0]) + str.Remove(0, 1);
}
If you are sure that str variable is valid (never an empty-string or null), try:
str = Char.ToUpper(str[0]) + str[1..];
Unlike the other solutions that use Substring, this one does not do additional string allocations. This example basically concatenates char with ReadOnlySpan<char>.
I realize this is an old post, but I recently had this problem and solved it with the following method.
private string capSentences(string str)
{
string s = "";
if (str[str.Length - 1] == '.')
str = str.Remove(str.Length - 1, 1);
char[] delim = { '.' };
string[] tokens = str.Split(delim);
for (int i = 0; i < tokens.Length; i++)
{
tokens[i] = tokens[i].Trim();
tokens[i] = char.ToUpper(tokens[i][0]) + tokens[i].Substring(1);
s += tokens[i] + ". ";
}
return s;
}
In the sample below clicking on the button executes this simple code outBox.Text = capSentences(inBox.Text.Trim()); which pulls the text from the upper box and puts it in the lower box after the above method runs on it.
Take the first letter out of the word and then extract it to the other string.
strFirstLetter = strWord.Substring(0, 1).ToUpper();
strFullWord = strFirstLetter + strWord.Substring(1);
text = new String(
new [] { char.ToUpper(text.First()) }
.Concat(text.Skip(1))
.ToArray()
);
this functions makes capital the first letter of all words in a string
public static string FormatSentence(string source)
{
var words = source.Split(' ').Select(t => t.ToCharArray()).ToList();
words.ForEach(t =>
{
for (int i = 0; i < t.Length; i++)
{
t[i] = i.Equals(0) ? char.ToUpper(t[i]) : char.ToLower(t[i]);
}
});
return string.Join(" ", words.Select(t => new string(t)));;
}
string str = "it is a text";
// first use the .Trim() method to get rid of all the unnecessary space at the begining and the end for exemple (" This string ".Trim() is gonna output "This string").
str = str.Trim();
char theFirstLetter = str[0]; // this line is to take the first letter of the string at index 0.
theFirstLetter.ToUpper(); // .ToTupper() methode to uppercase the firstletter.
str = theFirstLetter + str.substring(1); // we add the first letter that we uppercased and add the rest of the string by using the str.substring(1) (str.substring(1) to skip the first letter at index 0 and only print the letters from the index 1 to the last index.)
Console.WriteLine(str); // now it should output "It is a text"
static String UppercaseWords(String BadName)
{
String FullName = "";
if (BadName != null)
{
String[] FullBadName = BadName.Split(' ');
foreach (string Name in FullBadName)
{
String SmallName = "";
if (Name.Length > 1)
{
SmallName = char.ToUpper(Name[0]) + Name.Substring(1).ToLower();
}
else
{
SmallName = Name.ToUpper();
}
FullName = FullName + " " + SmallName;
}
}
FullName = FullName.Trim();
FullName = FullName.TrimEnd();
FullName = FullName.TrimStart();
return FullName;
}
string Input = " it is my text";
Input = Input.TrimStart();
//Create a char array
char[] Letters = Input.ToCharArray();
//Make first letter a capital one
string First = char.ToUpper(Letters[0]).ToString();
//Concatenate
string Output = string.Concat(First,Input.Substring(1));
Try this code snippet:
char nm[] = "this is a test";
if(char.IsLower(nm[0])) nm[0] = char.ToUpper(nm[0]);
//print result: This is a test

Categories

Resources