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+= " ";
}
Related
I have a string like AX_1234X_12345_X_CXY, I want to remove X from after the first underscore _ i.e. from 1234X to 1234. So final output will be like AX_1234_12345_X_CXY. How to do it?? If I use .Replace("X", "") it will replace all X which I don't want
You can iterate trough the string from the first occurrence of '_' .
you can find the first occurrence of '_' using IndexOf().
when loop will get to 'X' it will not append it to the "fixed string".
private static void Func()
{
string Original = "AX_1234X_12345_X_CXY";
string Fixed = Original.Substring(0, Original.IndexOf("_", 0));
// in case you want to remove all 'X`s' after first occurrence of `'_'`
// just dont use that variable
bool found = false;
for (int i = Original.IndexOf("_", 0); i < Original.Length; i++)
{
if (Original[i].ToString()=="X" && found == false)
{
found = true;
}
else
{
Fixed += Original[i];
}
}
Console.WriteLine(Fixed);
Console.ReadLine();
}
Why not good old IndexOf and Substring?
string s = "AX_1234X_12345_X_CXY";
int pUnder = s.IndexOf('_');
if (pUnder >= 0) { // we have underscope...
int pX = s.IndexOf('X', pUnder + 1); // we should search for X after the underscope
if (pX >= 0) // ...as well as X after the underscope
s = s.Substring(0, pX) + s.Substring(pX + 1);
}
Console.Write(s);
Outcome:
AX_1234_12345_X_CXY
string original = #"AX_1234X_12345_X_CXY";
original = #"AX_1234_12345_X_CXY";
One way is String.Remove, because you can tell exactly where to remove from. If the offending "X" is always in the same place, you can use:
string newString = old.Remove(7,1);
This will remove 1 character starting as position 7 (counting from zero as the beginning of the string).
If not always in the same character position, you might try:
int xPos = old.IndexOf("X");
string newString = old.Remove(xPos,1);
EDIT:
Based on OP comment, the "X" we're targeting occurs just after the first underscore character, so let's index off of the first underscore:
int iPosUnderscore = old.IndexOf("_");
string newString = old.Remove(iPosUnderscore + 1 ,1); // start after the underscore
Try looking at string.IndexOf or string.IndexOfAny
string s = "AX_1234X_12345_X_CXY";
string ns = HappyChap(s);
public string HappyChap(string value)
{
int start = value.IndexOf("X_");
int next = start;
next = value.IndexOf("X_", start + 1);
if (next > 0)
{
value = value.Remove(next, 1);
}
return value;
}
If and only if this is always the format then it should be a simple matter of combining substrings of the original text without including the x in that position. But the op hasn't stated that this is always the case. So if this is always the format and the same character position is always removed then you could simply just
string s = "AX_1234X_12345_X_CXY";
string newstring = s.Substring(0, 7) + s.Substring(8);
OK, based on only the second set of numbers being variable in length, you could then do something like:
int startpos = s.IndexOf('_', 4);
string newstring = s.Substring(0, startpos - 1) + s.Substring(startpos);
with this code, the following tests resulted in:
"AX_1234X_12345_X_CXY" became "AX_1234_12345_X_CXY"
"AX_123X_12345_X_CXY" became "AX_123_12345_X_CXY"
"AX_234X_12345_X_CXY" became "AX_234_12345_X_CXY"
"AX_1X_12345_X_CXY" became "AX_1_12345_X_CXY"
Something like this could work. I'm sure there's a more elegant solution.
string input1 = "AX_1234X_12345_X_CXY";
string pattern1 = "^[A-Z]{1,2}_[0-9]{1,4}(X)";
string newInput = string.Empty;
Match match = Regex.Match(input1, pattern1);
if(match.Success){
newInput = input1.Remove(match.Groups[1].Index, 1);
}
Console.WriteLine(newInput);
I am using string builder to format my string to append and prepend white spaces at the start and end of the string
here is what I have so far:
private void button1_Click(object sender, EventArgs e)
{
String Word = textBox1.Text;
AppendPrependText(Word);
}
private void AppendPrependText (String Word)
{
int count = Convert.ToInt32(textBox2.Text);
int WordCount = Word.Count();
int totalChar = count + WordCount;
string format = "{-"+totalChar+ "," +totalChar+ "}";
StringBuilder sb = new StringBuilder();
sb.AppendLine(string.Format(format, Word));
textBox3.Text = sb.ToString();
}
but I'm getting the error incorrect format. What am i doing wrong?
I think you need not to use separate operation for formatting the string, you can use .AppendFormat() method of the StringBuilder Class. Here is a sample code for you:
StringBuilder sbAppendFormat = new StringBuilder();
int numberOfSpaces=0;
if(int.TryParse(textBo2.Text, out numberOfSpaces))
{
string whiteSpaceSequence= new string(' ',numberOfSpaces);
sbAppendFormat.AppendFormat("{0}{1}{0}", whiteSpaceSequence, "This is your String");
}
textBox3.Text = sbAppendFormat.ToString();
Note:- Assume that you need to add Some white spaces(let it be 5) before and after the specific word.
There's two issues here. The first is that you're correctly using a StringBuilder to format a string which reduces the overhead caused by concatenation but you're also performing extra concatenation on that format local variable.
The second issue is that your format string is wrong: it doesn't include the argument index. Your method expects a single word, so that index should be zero before the padding instruction.
Fortunately, you could skip past the concatenation of the format string and simply append your user-defined space (or whatever character) to the fresh instance of the StringBuilder
Your code has some errors:
Format Exception will be thrown by this line for sure:
sb.AppendLine(string.Format(format, Word));
Your current format doesn't contain any {0} in which the Word value should be replaced.
//you should put here somewhere {0} in the format or remove the Word for string.Format
//for an example
string format = "{-" + totalChar + "," + totalChar + "}{0}";
Also this line is possible Format Exception if the textBox2.Text is for an example a11:
int count = Convert.ToInt32(textBox2.Text);
You need to use int.TryParse
int count = 0;
int.TryParse(textBo2.Text, out count);
What seems to be the issue is
string format = "{-"+totalChar+ "," +totalChar+ "}";
Letz say if totalChar = 10; than
format = "{-10,10}"
which is not a valid format whereas it should be
{0,10}{1,10}
and thus your string would look like
Console.WriteLine(string.Format("{0,10}{1,10}", "Mohit",""));
The third argument was intentionally left blank so that nothing would be printed after the word. but you will have 10 spaces.
But I would recommend you to use String.PadRight and String.PadLeft instead.
An example to demostrate your task using PadLeft and PadRight
int count = 5;
string st = "mohit ";
int WordCount = st.Count();
int totalChar = count + WordCount;
st = st.PadRight(totalChar, ' ');
st = st.PadLeft(totalChar + count, ' ');
Console.WriteLine(st);
For simple adding spaces or chars, in front and/or back, Padding will work fine.
private void button1_Click(object sender, EventArgs e)
{
int amount;
int.TryParse(textBox2.Text, out amount);
var str = textBox1.Text.PadLeft(amount + textBox1.TextLength);
str = str.PadRight(amount + str.Length);
textBox3.Text = str;
}
Then you can choose a spacer (paddingChar) also later if needed/wanted
var str = textBox1.Text.PadLeft(amount + textBox1.TextLength, '>');
str = str.PadRight(amount + str.Length, '<');
Additionally with an extra method:
private void button1_Click(object sender, EventArgs e)
{
textBox3.Text = Format(textBox1.Text, textBox2.Text);
}
private string Format(string word, string spaces)
{
int amount;
int.TryParse(spaces, out amount);
var str = word.PadLeft(amount + word.Length);
str = str.PadRight(amount + str.Length);
return str;
}
I did not use StringBuilder, I returned a String from AppendPrependText. The if statement checks for invalid integer input in textBox2, if its invalid return the original string. If it is a valid integer, create a padString with count number of spaces then return the original string sandwiched between two of the padStrings.
EDIT: added check for negative numbers by adding AND count > 0 to the if statement.
private String AppendPrependText(String Word)
{
int count = 0;
if (int.TryParse(textBox2.Text, out count) && count > 0)
{
String padString = "".PadLeft(count, ' ');
return padString + Word.ToString() + padString;
}
else
{
return Word;
}
}
private void button1_Click_1(object sender, EventArgs e)
{
String Word = textBox1.Text;
textBox3.Text = ">" + AppendPrependText(Word) + "<";
}
Suppose I have a string A, for example:
string A = "Hello_World";
I want to remove all characters up to (and including) the _. The exact number of characters before the _ may vary. In the above example, A == "World" after removal.
string A = "Hello_World";
string str = A.Substring(A.IndexOf('_') + 1);
You have already received a perfectly fine answer. If you are willing to go one step further, you could wrap up the a.SubString(a.IndexOf('_') + 1) in a robust and flexible extension method:
public static string TrimStartUpToAndIncluding(this string str, char ch)
{
if (str == null) throw new ArgumentNullException("str");
int pos = str.IndexOf(ch);
if (pos >= 0)
{
return str.Substring(pos + 1);
}
else // the given character does not occur in the string
{
return str; // there is nothing to trim; alternatively, return `string.Empty`
}
}
which you would use like this:
"Hello_World".TrimStartUpToAndIncluding('_') == "World"
string a = "Hello_World";
a = a.Substring(a.IndexOf("_")+1);
try this? or is the A= part in your A=Hello_World included?
var foo = str.Substring(str.IndexOf('_') + 1);
string orgStr = "Hello_World";
string newStr = orgStr.Substring(orgStr.IndexOf('_') + 1);
you can do this by creating a substring.
simple exampe is here:
public static String removeTillWord(String input, String word) {
return input.substring(input.indexOf(word));
}
removeTillWord("I need this words removed taken please", "taken");
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);
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