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
Related
Trying to make hangman (i'm still a newbie) and the program chooses a random word out of a textfile ==> word turned into arrays. And i have to put it in a label while having the textlabel modified to what's in the letterlist. Thing is: it doesn't show anything in the label and i can't seem to figure out why.
So the for-loop is the modifier and when it has modified every string in the list it should return the word with the right letter or "_".
At first i tried is by doing: letterlist[i] = Letter or letterlist[i] = "_", but would happen is if i typed in a right letter it would show only that letter.
For example: word = "pen". If i typed in "p", it resulted in "ppp".
letterlist = new List<string>();
char[] wordarray = woord.GetWordcharArray(); //word in charArrays
string newwordstring = new string(wordarray);
for (int i = 0; i < wordarray.Length; i++)
{
letterlist.Add(" "); //adds empty strings in list with the length of the word
}
/*
* For-loop for every string in List to check and modify if it's correct or not
*/
for (int i = 0; i < letterlist.Count; i++)
{
if (letterlist[i].Contains(Letter) && newwordstring.Contains(Letter)) //right answer: letter[i] = Letter
{
letterlist[i].Replace(Letter, Letter);
}
else if (letterlist[i].Contains(" ") && newwordstring.Contains(Letter)) //right answer: letter[i] = ""
{
letterlist[i].Replace(" ", Letter);
}
else if (letterlist[i].Contains("_") && newwordstring.Contains(Letter)) //right answer: letter[i] = "_"
{
letterlist[i].Replace("_", Letter);
}
else if (letterlist[i].Contains(" ") && !newwordstring.Contains(Letter)) //wrong answer: letter[i] = ""
{
letterlist[i].Replace(" ", "_");
}
else if (letterlist[i].Contains("_") && !newwordstring.Contains(Letter)) //wrong answer: letter[i] = "_"
{
letterlist[i].Replace(" ", "_");
}
}
/*
* empty += every modified letterlist[i]-string
*/
string empty = "";
foreach (string letter in letterlist)
{
empty += letter;
}
return empty;
New code but it only shows "___" ("_" as many times as the amount of letters as word has):
char[] wordarray = woord.GetWordcharArray(); //word in charArrays
string newwordstring = new string(wordarray); //actual word
string GuessedWord = new string('_', newwordstring.Length);//word that shows in form
bool GuessLetter(char letterguess)
{
bool guessedright = false;
StringBuilder builder = new StringBuilder(GuessedWord);
for(int i = 0; i < GuessedWord.Length; i++)
{
if(char.ToLower(wordarray[i]) == Convert.ToChar(Letter))
{
builder[i] = wordarray[i];
guessedright = true;
}
}
GuessedWord = builder.ToString();
return guessedright;
}
return GuessedWord;
First of all, note that C# string are immutable, which means letterlist[i].Replace(" ", "_") does not replace spaces with underscores. It returns a new string in which spaces have been replaced with underscores.
Therefore, you should reassign this result:
letterlist[i] = letterlist[i].Replace(" ", "_");
Second, Replace(Letter, Letter) won't do much.
Third, in your first for loop, you set every item in letterlist to " ".
I don't understand then why you expect (in your second for loop) letterlist[i].Contains("_") to ever be true.
Finally, I'll leave here something you might find interesting (especially the use of StringBuilder):
class Hangman
{
static void Main()
{
Hangman item = new Hangman();
item.Init();
Console.WriteLine(item.Guessed); // ____
item.GuessLetter('t'); // true
Console.WriteLine(item.Guessed); // T__t
item.GuessLetter('a'); // false
Console.WriteLine(item.Guessed); // T__t
item.GuessLetter('e'); // true
Console.WriteLine(item.Guessed); // Te_t
}
string Word {get;set;}
string Guessed {get;set;}
void Init()
{
Word = "Test";
Guessed = new string('_',Word.Length);
}
bool GuessLetter(char letter)
{
bool guessed = false;
// use a stringbuilder so you can change any character
var sb = new StringBuilder(Guessed);
// for each character of Word, we check if it is the one we claimed
for(int i=0; i<Word.Length; i++)
{
// Let's put both characters to lower case so we can compare them right
if(Char.ToLower(Word[i]) == Char.ToLower(letter)) // have we found it?
{
// Yeah! So we put it in the stringbuilder at the same place
sb[i] = Word[i];
guessed = true;
}
}
// reassign the stringbuilder's representation to Guessed
Guessed = sb.ToString();
// tell if you guessed right
return guessed;
}
}
I was trying to remove spaces before sentence ending but had no success. I was thinking of doing it with Split function but it didn't go well. The only thing I succeeded at was adding spaces after sentence ending. Here is my code:
static void Main(string[] args)
{
System.Windows.Forms.OpenFileDialog dlgOpen = new System.Windows.Forms.OpenFileDialog();
if (dlgOpen.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
StreamReader sr = new StreamReader(dlgOpen.FileName);
string dat1 = sr.ReadToEnd();
string dat2 = Path.GetDirectoryName(dlgOpen.FileName);
string dat3 = Path.GetFileNameWithoutExtension(dlgOpen.FileName);
string dat4 = Path.GetExtension(dlgOpen.FileName);
dat2 = dat2 + "/" + dat3 + "_norm" + dat4;
sz1(ref dat1);
Console.Write(dat1);
StreamWriter sw = new StreamWriter(dat2, false);
sw.WriteLine(dat1);
sw.Flush();
sw.Close();
Console.ReadLine();
}
}
static void sz1(ref string dat1)
{
char[] ArrayCharacters = { '.', ':', ',', ';', '!', '?' };
int i = -1;
dat1 = dat1.Trim();
for (int k = 0; k < dat1.Length; k++)
{
dat1 = dat1.Replace(" ", " ");
}
do
{
i = dat1.IndexOfAny(ArrayCharacters, i + 1);
if (i != -1)
{
dat1 = dat1.Insert((i + 1), " ");
dat1 = dat1.Replace(" ", " ");
}
} while (i != -1);
do
{
i = dat1.IndexOfAny(ArrayCharacters, i + 1);
if (i != -1)
{
dat1 = dat1.Insert((i - 1), " ");
dat1 = dat1.Replace(" ", " ");
dat1 = dat1.Remove(i - 1, 1);
}
} while (i != -1);
}
One option is using regex:
string pattern = "\\s+$";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(dat1, replacement);
If you're just learning programming, then one solution that you should be familiar with is to use a loop to walk the string one character at a time, and since we're examining the end of the string, it makes sense to walk it backwards.
I'm assuming from your code (though it would be nice if you clarified it in your question) that you have a set of characters that are allowed at the end of a sentence, and you would like to leave these characters alone, but remove any additional spaces.
The logic, then, would be to start from the end of the string, and if a character is a valid ending character leave it alone. Otherwise, if it's a space, remove it. And finally, if it's neither then we're done.
Below is a method that uses this logic, along with a StringBuilder variable that is used to store the result. Starting at the end of the string, we capture the last characters, adding them to the result if they're valid and skipping them if they're spaces, until we reach a "regular" character, at which point we keep the rest of the string:
static string TrimEndSpaces(string input)
{
// If the input is null, there's nothing to do - just return null
if (input == null) return input;
// Our array of valid ending punctuation
char[] validEndingPunctuation = { '.', ':', ',', ';', '!', '?' };
// This will contain our final result
var result = new StringBuilder();
// Walk backwards through the input string
for (int i = input.Length - 1; i >= 0; i--)
{
if (validEndingPunctuation.Contains(input[i]))
{
// Valid character, so add it and keep going backwards
result.Insert(0, input[i]);
continue;
}
if (input[i] == ' ')
{
// Space character at end - skip it
continue;
}
// Regular character found - we're done. Add the rest of the string
result.Insert(0, input.Substring(0, i + 1));
break;
}
return result.ToString();
}
And here is an example usage, with some test sentences with varying endings of spaces, valid characters, null strings, empty strings, etc:
private static void Main()
{
var testInput = new List<string>
{
null,
"",
" ",
"Normal sentence test.",
"Test with spaces .",
"Test with multiple ending chars !?!?!",
"Test with only spaces at end ",
"Test with spaces after punctuation. ",
"Test with mixed punctuation and spaces ! ? ! ? ! "
};
foreach (var test in testInput)
{
// Format output so we can "see" null and empty strings
var original = test ?? "<null>";
if (original.Length == 0) original = "<empty>";
// Show original and the result. Wrap result in <> so we know where it ends.
Console.WriteLine($"{original.PadRight(50, '-')} = <{TrimEndSpaces(test)}>");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output
If you just want to remove them from the end, you can use:
if(myString.EndsWith(" ") == true)
{
myString = myString.TrimEnd();
}
Of course, you will need to consider the ending symbol ".", "!" or "?", you might want to exclude that char if the spaces are just before it.
Another approach would be:
var keepTrimming = true;
while(keepTrimming == true)
{
if(myString.EndsWith(" ") == true)
{
myString= myString.Remove(myString.Length - 1);
}
else
{
keepTrimming = false
}
}
If I have a string value like this "1234-", then I need to split till the non-numeric character that is - and add numeric value 1 after the non-numeric char. later I have to update the value to "1234-1". Then the program will check with the last updated value 1234-1 then it will increment by 1 every time and store it for future use. If no non-numeric in a string then the program will increment by 1 with the numeric string.
Below are some examples of String and Output Value
Ex Str1 Output
2014- 2014-1
2014-1 2014-2
AAA AAA1
ABC-ABC ABC-ABC1
12345 12346
1234AA 1234AA1
I have used the below code before.
Code
var SiteFile = (from site in db.SiteFiles where site.Code == "ACQPONUM" select site.Line2).FirstOrDefault(); // Get Input string to generate AUTO number.
int Count = (from Porders in db.Porders where Porders.No.StartsWith(SiteFile) select Porders.No).ToList().Count; // Get the count of matching values in db.
var PONo = (from Porders in db.Porders where Porders.No.StartsWith(SiteFile) select Porders.No).ToList(); // Get list of Matching existing values.
if (Count != 0)
{
if (PONo != null)
{
int Val = (from PONos in PONo let value = Regex.Match(PONos, #"\d+").Value select Convert.ToInt32(value == string.Empty ? "0" : Regex.Match(PONos, #"\d+").Value) + 1).Concat(new[] { 0 }).Max(); // Fiind the maximum value in the matched list nd Increment value by if same type exists in the db.
porder.No = SiteFile + Val.ToString();
}
}
else
{
porder.No = SiteFile + "1";
}
Any help to this will be appreciated.
Maybe something like this:
string s = "123419";
string res = null;
char ch = s[s.Length - 1];
if(char.IsDigit(ch)) // handle numbers
{
res = s.Substring(0,s.Length - 1);
string suffix = null;
// special case
if(ch == '9'){
suffix = "10";
}
else
{
suffix = (++ch).ToString();
}
res += suffix;
}
else
{
res = string.Format("{0}1", s);
}
Try this code:
private string Incrementvalue(string str)
{
string retVal;
if (str.Contains(DELIMITER))
{
string[] parts = str.Split(new char[] { DELIMITER }, 2);
string origSuffix = parts[1];
string newSuffix;
int intSuffix;
if (int.TryParse(origSuffix, out intSuffix))
//Delimiter exists and suffix is already a number: Increment!
newSuffix = (intSuffix + 1).ToString();
else
//Delimiter exists and suffix is NTO number: Add a "1" suffix.
newSuffix = origSuffix + 1;
retVal = parts[0] + DELIMITER + newSuffix;
}
else
{
int temp;
if (int.TryParse(str, out temp))
{
//Delimiter does not exists and the input is a number: Increment last digit!
string newSuffix = (int.Parse(str[str.Length - 1].ToString()) + 1).ToString();
retVal = str.Substring(0, str.Length - 1) + newSuffix;
retVal = str.Substring(0, str.Length - 1) + newSuffix;
}
else
{
//Delimiter does not exists and the input is NOT a number: Add a "1" suffix.
retVal = str + "1";
}
}
return retVal;
}
The code could be written in a much more compact manner, but think this will be more readable and it will work...
Ok I currently have this code
public int i = 0; //this is outside of the private void button1_click
string str = txtEmail.Text;
int pos = str.LastIndexOf("#");
string str2 = str.Substring(pos);
string str3 = str.Substring(0, str.LastIndexOf("#"));
txtEmail.Text = str3 + i++ + str2;
it splits the email into 2 string then combines them with an integer between them, But I want it to change the integer. But that code just makes it lets saying the text becomes awesome1#email.com when i press the button to increase the 1 to a 2 it just does this instead. awesome12#email.com and so on. how do i get it to just add 1 to the 1 and not put a 2 next to the 1?
I tested the following and it looks like it solves your problem. Change this line of yours:
string str = txtEmail.Text;
To this:
string str = txtEmail.Text.Replace(string.Format("{0}#", i - 1), "#");
It sets it up so that your email addresses will be in the form of:
awesome1#email.com
awesome2#email.com
awesome3#email.com
etc.
Not sure where i is coming from in this code but hopefully this will work
string str = txtEmail.Text;
int pos = str.LastIndexOf("#");
string str2 = str.Substring(pos);
string str3 = str.Substring(0, str.LastIndexOf("#"));
txtEmail.Text = str3 + (i++).ToSting() + str2;
This should work:
String email = "awesome1#email.com";
String[] tokens = email.Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
const String allowed = "0123456789";
String part1 = "";
String numberStr = "";
foreach (char c in tokens[0].Reverse())
{
if (allowed.Contains(c) && part1.Length==0)
{
numberStr += c;
}
else
{
part1 += c;
}
}
part1 = new String(part1.Reverse().ToArray());
int number = int.Parse(new String(numberStr.Reverse().ToArray()));
String result = String.Format("{0}{1}#{2}", part1, number++, tokens[1]);
Although it looks a little bit cumbersome. Accept a Regex answer if there's one.
This will work
public static string IncNumberBeforeAt(string text)
{
int lastAt = text.LastIndexOf('#');
if (lastAt != -1)
{
int pos = lastAt - 1;
string num = "";
while (text[pos] >= '0' && text[pos] <= '9')
{
num = text[pos] + num;
pos--;
if (pos < 0)
break;
}
int numInc = int.Parse(num) + 1;
return text.Replace(num.ToString() + "#", numInc.ToString() + "#");
}
else
{
return text;
}
}
test
IncNumberBeforeAt("awesome1#email.com"); // => returns awesome2#email.com
IncNumberBeforeAt("awesome234#email.com"); // => returns awesome235#email.com
IncNumberBeforeAt("email.com"); // => returns email.com
IncNumberBeforeAt("5#email.com"); // => returns 6#email.com
You will have to keep track of your original e-mail address:
e.g.
string originalEmail = "test#gmail.com";
var parts = originalEmail.Split('#');
txtEmail.Text = string.Format("{0}{1}#{2}", parts[0], i++, parts[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