How to make a first letter capital in C# - 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

Related

Remove text between quotes

I have a program, in which you can input a string. But I want text between quotes " " to be removed.
Example:
in: Today is a very "nice" and hot day.
out: Today is a very "" and hot day.
Console.WriteLine("Enter text: ");
text = Console.ReadLine();
int letter;
string s = null;
string s2 = null;
for (s = 0; s < text.Length; letter++)
{
if (text[letter] != '"')
{
s = s + text[letter];
}
else if (text[letter] == '"')
{
s2 = s2 + letter;
letter++;
(text[letter] != '"')
{
s2 = s2 + letter;
letter++;
}
}
}
I don't know how to write the string without text between quotes to the console.
I am not allowed to use a complex method like regex.
This should do the trick. It checks every character in the string for quotes.
If it finds quotes then sets a quotesOpened flag as true, so it will ignore any subsequent character.
When it encounters another quotes, it sets the flag to false, so it will resume copying the characters.
Console.WriteLine("Enter text: ");
text = Console.ReadLine();
int letterIndex;
string s2 = "";
bool quotesOpened = false;
for (letterIndex= 0; letterIndex< text.Length; letterIndex++)
{
if (text[letterIndex] == '"')
{
quotesOpened = !quotesOpened;
s2 = s2 + text[letterIndex];
}
else
{
if (!quotesOpened)
s2 = s2 + text[letterIndex];
}
}
Hope this helps!
A take without regular expressions, which I like better, but okay:
string input = "abc\"def\"ghi";
string output = input;
int firstQuoteIndex = input.IndexOf("\"");
if (firstQuoteIndex >= 0)
{
int secondQuoteIndex = input.IndexOf("\"", firstQuoteIndex + 1);
if (secondQuoteIndex >= 0)
{
output = input.Substring(0, firstQuoteIndex + 1) + input.Substring(secondQuoteIndex);
}
}
Console.WriteLine(output);
What it does:
It searches for the first occurrence of "
Then it searches for the second occurrence of "
Then it takes the first part, including the first " and the second part, including the second "
You could improve this yourself by searching until the end of the string and replace all occurrences. You have to remember the new 'first index' you have to search on.
string text = #" Today is a very ""nice"" and hot day. Second sentense with ""text"" test";
Regex r = new Regex("\"([^\"]*)\"");
var a = r.Replace(text,string.Empty);
Please try this.
First we need to split string and then remove odd items:
private static String Remove(String s)
{
var rs = s.Split(new[] { '"' }).ToList();
return String.Join("\"\"", rs.Where(_ => rs.IndexOf(_) % 2 == 0));
}
static void Main(string[] args)
{
var test = Remove("hello\"world\"\"yeah\" test \"fhfh\"");
return;
}
This would be a possible solution:
String cmd = "This is a \"Test\".";
// This is a "".
String newCmd = cmd.Split('\"')[0] + "\"\"" + cmd.Split('\"')[2];
Console.WriteLine(newCmd);
Console.Read();
You simply split the text at " and then add both parts together and add the old ". Not a very nice solution, but it works anyway.
€dit:
cmd[0] = "This is a "
cmd[1] = "Test"
cmd[2] = "."
You can do it like this:
Console.WriteLine("Enter text: ");
var text = Console.ReadLine();
var skipping = false;
var result = string.Empty;
foreach (var c in text)
{
if (!skipping || c == '"') result += c;
if (c == '"') skipping = !skipping;
}
Console.WriteLine(result);
Console.ReadLine();
The result string is created by adding characters from the original string as long we are not between quotes (using the skipping variable).
Take all indexes of quotes remove the text between quotes using substring.
static void Main(string[] args)
{
string text = #" Today is a very ""nice"" and hot day. Second sentense with ""text"" test";
var foundIndexes = new List<int>();
foundIndexes.Add(0);
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '"')
foundIndexes.Add(i);
}
string result = "";
for(int i =0; i<foundIndexes.Count; i+=2)
{
int length = 0;
if(i == foundIndexes.Count - 1)
{
length = text.Length - foundIndexes[i];
}
else
{
length = foundIndexes[i + 1] - foundIndexes[i]+1;
}
result += text.Substring(foundIndexes[i], length);
}
Console.WriteLine(result);
Console.ReadKey();
}
Output: Today is a very "" and hot day. Second sentense with "" test";
Here dotNetFiddle

Alternatively upper- and lowercase words in a string

I use Visual Studio 2010 ver.
I have array strings [] = { "eat and go"};
I display it with foreach
I wanna convert strings like this : EAT and GO
Here my code:
Console.Write( myString.First().ToString().ToUpper() + String.Join("",myString].Skip(1)).ToLower()+ "\n");
But the output is : Eat and go . :D lol
Could you help me? I would appreciate it. Thanks
While .ToUpper() will convert a string to its upper case equivalent, calling .First() on a string object actually returns the first element of the string (since it's effectively a char[] under the hood). First() is actually exposed as a LINQ extension method and works on any collection type.
As with many string handling functions, there are a number of ways to handle it, and this is my approach. Obviously you'll need to validate value to ensure it's being given a long enough string.
using System.Text;
public string CapitalizeFirstAndLast(string value)
{
string[] words = value.Split(' '); // break into individual words
StringBuilder result = new StringBuilder();
// Add the first word capitalized
result.Append(words[0].ToUpper());
// Add everything else
for (int i = 1; i < words.Length - 1; i++)
result.Append(words[i]);
// Add the last word capitalized
result.Append(words[words.Length - 1].ToUpper());
return result.ToString();
}
If it's always gonna be a 3 words string, the you can simply do it like this:
string[] mystring = {"eat and go", "fast and slow"};
foreach (var s in mystring)
{
string[] toUpperLower = s.Split(' ');
Console.Write(toUpperLower.First().ToUpper() + " " + toUpperLower[1].ToLower() +" " + toUpperLower.Last().ToUpper());
}
If you want to continuously alternate, you can do the following:
private static string alternateCase( string phrase )
{
String[] words = phrase.split(" ");
StringBuilder builder = new StringBuilder();
//create a flag that keeps track of the case change
book upperToggle = true;
//loops through the words
for(into i = 0; i < words.length; i++)
{
if(upperToggle)
//converts to upper if flag is true
words[i] = words[i].ToUpper();
else
//converts to lower if flag is false
words[i] = words[i].ToLower();
upperToggle = !upperToggle;
//adds the words to the string builder
builder.append(words[i]);
}
//returns the new string
return builder.ToString();
}
Quickie using ScriptCS:
scriptcs (ctrl-c to exit)
> var input = "Eat and go";
> var words = input.Split(' ');
> var result = string.Join(" ", words.Select((s, i) => i % 2 == 0 ? s.ToUpperInvariant() : s.ToLowerInvariant()));
> result
"EAT and GO"

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

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+= " ";
}

C# fix sentence

I need to take a sentence in that is all on one line with no spaces and each new word has a captial letter EX. "StopAndSmellTheRoses" and then convert it to "Stop and smell the roses" This is my function that I have but I keep getting an argument out of range error on the insert method. Thanks for any help in advance.
private void FixSentence()
{
// String to hold our sentence in trim at same time
string sentence = txtSentence.Text.Trim();
// loop through the string
for (int i = 0; i < sentence.Length; i++)
{
if (char.IsUpper(sentence, i) & sentence[i] != 0)
{
// Change to lowercase
char.ToLower(sentence[i]);
// Insert space behind the character
// This is where I get my error
sentence = sentence.Insert(i-1, " ");
}
}
// Show our Fixed Sentence
lblFixed.Text = "";
lblFixed.Text = "Fixed: " + sentence;
}
The best way to build up a String in this manner is to use a StringBuilder instance.
var sentence = txtSentence.Text.Trim();
var builder = new StringBuilder();
foreach (var cur in sentence) {
if (Char.IsUpper(cur) && builder.Length != 0) {
builder.Append(' ');
}
builder.Append(cur);
}
// Show our Fixed Sentence
lblFixed.Text = "";
lblFixed.Text = "Fixed: " + builder.ToString();
Using the Insert method creates a new string instance every time resulting in a lot of needlessly allocated values. The StringBuilder though won't actually allocate a String until you call the ToString method.
You can't modify the sentence variable in the loop that is going through it.
Instead, you need to have a second string variable that you append all of the found words.
Here is the answer
var finalstr = Regex.Replace(
"StopAndSmellTheRoses",
"(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])|(?<=[^0-9])(?<x>[0-9])(?=.)",
me => " " + me.Value.ToLower()
);
will output
Stop and smell the roses
Another version:
public static class StringExtensions
{
public static string FixSentence(this string instance)
{
char[] capitals = Enumerable.Range(65, 26).Select(x => (char)x).ToArray();
string[] words = instance.Split(capitals);
string result = string.Join(' ', words);
return char.ToUpper(result[0]) + result.Substring(1).ToLower();
}
}

Categories

Resources