How do I alternate the case in a string? - c#

I need to alternate the case in a sentence and I don't know how to.
For example:
thequickbrownfoxjumpsoverthelazydog
to
GoDyZaLeHtReVoSpMuJxOfNwOrBkCiUqEhT
this is my code so far
Console.WriteLine("Please enter a sentence:");
string text = Console.ReadLine();
text = text.Replace(" ", "");
char[] reversed = text.ToCharArray();//String to char
Array.Reverse(reversed);//Reverses char
new string(reversed);//Char to string
Console.WriteLine(reversed);
Console.ReadLine();
Please note that there are no spaces for a reason as that's also part of the homework task.

A string is immutable, so, you need to convert it to a char[].
char[] characters = text.ToCharArray();
for (int i = 0; i < characters.Length; i+=2) {
characters[i] = char.ToUpper(characters[i]);
}
text = new string(characters);

There is no point to reverse your string. Just upper case your even number indexed characters in your string.
Remember, my culture is tr-TR and this String.ToUpper method works depends on your current thread culture. In this example, your output can be different than mine.
Here an example in LINQPad;
string s = "thequickbrownfoxjumpsoverthelazydog";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (i % 2 == 0)
{
sb.Append(s[i].ToString().ToUpper());
}
else
{
sb.Append(s[i].ToString());
}
}
sb.ToString().Dump();
Output will be;
ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG

Another possible solution with LINQ can be done in one line like this:
string s = "thequickbrownfoxjumpsoverthelazydog";
string result = new String(s
// take each character
.ToCharArray()
// convert every character at even index to upper
.Select ((character, index) => (index % 2) == 0 ? Char.ToUpper(character) : character)
// back to array in order to create a string
.ToArray());
Console.WriteLine(result);
The output is:
ThEqUiCkBrOwNfOxJuMpSoVeRtHeLaZyDoG
This solution uses the indexed LINQ Select clause in order to access the current index and the value that is currently projected.

A one liner:
new string(myString.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray())
An extension method:
public static string AltCase(this string s)
{
return new string(s.Select((c, i) => i % 2 == 0 ? char.ToUpper(c) : c).ToArray());
}

Related

How to capitalize the first character of every sentence

Create an application with a method that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized.
This is what I have to far and I can't seem to get it right:
//Create method to process string.
private string Sentences(string input)
{
//Capitalize first letter of input.
char firstLetter = char.ToUpper(input[0]);
//Combine the capitalize letter with the rest of the input.
input = firstLetter.ToString() + input.Substring(1);
//Create a char array to hold all characters in input.
char[] letters = new char[input.Length];
//Read the characters from input into the array.
for (int i = 0; i < input.Length; i++)
{
letters[i] = input[i];
}
//Loop through array to test for punctuation and capitalize a character 2 index away.
for (int index = 0; index < letters.Length; index++)
{
if(char.IsPunctuation(letters[index]))
{
if (!((index + 2) >= letters.Length))
{
char.ToUpper(letters[index+ 2]);
}
}
}
for(int ind = 0; ind < letters.Length; ind++)
{
input += letters[ind].ToString();
}
return input;
}
You could use Linq.Aggregate n - see comments in code and code output for explanation how it work's.
This one will respect "Bla. blubb" as well - you need to check for whitespaces after ".?!"
using System;
using System.Linq;
internal class Program
{
static string Capitalize(string oldSentence )
{
return
// this will look at oldSentence char for char, we start with a
// new string "" (the accumulator, short acc)
// and inspect each char c of oldSentence
// comment all the Console.Writelines in this function, thats
// just so you see whats done by Aggregate, not needed for it to
// work
oldSentence
.Aggregate("", (acc, c) =>
{
System.Console.WriteLine("Accumulated: " + acc);
System.Console.WriteLine("Cecking: " + c);
// if the accumulator is empty or the last character of
// trimmed acc is a ".?!" we append the
// upper case of c to it
if (acc.Length == 0 || ".?!".Any(p => p == acc.Trim().Last())) // (*)
acc += char.ToUpper(c);
else
acc += c; // else we add it unmodified
System.Console.WriteLine($"After: {acc}\n");
return acc; // this returns the acc for the next iteration/next c
});
}
static void Main(string[] args)
{
Console.SetBufferSize(120, 1000);
var oldSentence = "This is a testSentence. some occurences "
+ "need capitalization! for examlpe here. or here? maybe "
+ "yes, maybe not.";
var newSentence = Capitalize(oldSentence);
Console.WriteLine(new string('*', 80));
Console.WriteLine(newSentence);
Console.ReadLine();
}
}
(*)
".?!".Any(p => p == ... )) means does the string ".?!" contain any character that equals ...
acc.Trim().Last() means: remove whitespaces in front/on end of acc and give me the last character
.Last() and .Any() are also Linq. Most of the Linq-esc extension can be found here: https://msdn.microsoft.com/en-us/library/9eekhta0(v=vs.110).aspx
Output (snipped - its rather longish ;o)
Accumulated:
Cecking: T
After: T
Accumulated: T
Cecking: h
After: Th
Accumulated: Th
Cecking: i
After: Thi
Accumulated: Thi
Cecking: s
After: This
Accumulated: This
Cecking:
After: This
Accumulated: This
Cecking: i
After: This i
Accumulated: This i
Cecking: s
After: This is
<snipp - .. you get the idea how Aggregate works ...>
Accumulated: This is a testSentence.
Cecking: s
After: This is a testSentence. S
<snipp>
Accumulated: This is a testSentence. Some occurences need capitalization!
Cecking: f
After: This is a testSentence. Some occurences need capitalization! F
<snipp>
********************************************************************************
This is a testSentence. Some occurences need capitalization! For examlpe here. Or here? Maybe yes, maybe not.
I would suggest to use a regex to identify all the dots in your sentence. Get the match, make it upper case and replace it back in the original sentence, in the match index. I dont actually have any IDE in which try the code on .NET right now but i can write it in pseudocode for better understanding.
String setence = "your.setence.goes.here";
Regex rx = new Regex("/\..*?[A-Z]/");
foreach (Match match in rx.Matches(sentence))
{
setence.remove(match.Index, 2).insert(match.Index, String.ToUpper(match.Value));
}
You have two tasks:
1) Split text into sentences
2) Capitalize the first char in the sentences
Task one can be very complex, e.g. because there a lot of crazy languages out there. Put since this is homework I assume you can go ahead and simply split by well know separators.
Task two is just about basic string operations. You select the first char, make it uppercase and add the missing part of the sentence via a substring operation.
Here is a code example:
char[] separators = new char[] { '!', '.', '?' };
string[] sentencesArray = "First sentence. second sentence!lastone.".Split(separators, StringSplitOptions.RemoveEmptyEntries);
var i = 0;
Array.ForEach(sentencesArray, e =>
{
sentencesArray[i] = e.Trim().First().ToString().ToUpper() +
e.Trim().Substring(1);
i++;
});
I Have created a method in Groovy for the same
String capitalizeFirstCharInSentence(String str) {
String result = ''
str = str.toLowerCase()
List<String> strings = str.tokenize('.')
strings.each { line ->
StringBuilder builder = new StringBuilder(line)
int i = 0
while (i < builder.size() - 1 && !Character.isLowerCase(builder.charAt(i))) {
i++
}
if (Character.isLowerCase(builder.charAt(i))) {
builder.setCharAt(i, builder.charAt(i).toUpperCase())
result += builder.toString() + '.'
}
}
return result
}
I liked the way you formatted your method because it made it easy for newer coders to read so I decided to try to make the code work while maintaining the structure. The main problem I saw was that you were not replacing the arrays after formatting them.
//Create method to process string.
private string Sentences(string input)
{
//Create a char array to hold all characters in input.
char[] letters = new char[input.Length];
//Read the characters from input into the array.
for (int i = 0; i < input.Length; i++)
{
letters[i] = input[i];
}
//Capitalize first letter of input.
letters[0] = char.ToUpper(letters[0]);
//Loop through array to test for punctuation and capitalize a character 2 index away.
for (int index = 0; index < letters.Length; index++)
{
if(char.IsPunctuation(letters[index]))
{
if (index + 2 <= letters.Length)
{
letters[index + 2] = char.ToUpper(letters[index+ 2]);
}
}
}
// convert array back to string
string results = new string(letters)
return results;
}

How find sub-string(0,91) from long string?

I write this program in c#:
static void Main(string[] args)
{
int i;
string ss = "fc7600109177";
// I want to found (0,91) in ss string
for (i=0; i<= ss.Length; i++)
if (((char)ss[i] == '0') && (((char)ss[i+1] + (char)ss[i+2]) == "91" ))
Console.WriteLine(" found");
}
What's wrong in this program and how can I find (0,91)?
First of all, you don't have to cast to char your ss[i] or others. ss[i] and others are already char.
As a second, you try to concatanate two char (ss[i+1] and ss[i+2]) in your if loop and after you check equality with a string. This is wrong. Change it to;
if ( (ss[i] == '0') && (ss[i + 1] == '9') && (ss[i + 2]) == '1')
Console.WriteLine("found");
As a third, which I think the most important, don't write code like that. You can easly use String.Contains method which does exactly what you want.
Returns a value indicating whether the specified String object occurs
within this string.
string ss = "fc7600109177";
bool found = ss.Contains("091");
Here a DEMO.
use "contain" return only true or false and "index of" return location
of string but I want to find location of "091" in ss and if "091"
repeat like: ss ="763091d44a0914" how can I find second "091" ??
Here how you can find all indexes in your string;
string chars = "091";
string ss = "763091d44a0914";
List<int> indexes = new List<int>();
foreach ( Match match in Regex.Matches(ss, chars) )
{
indexes.Add(match.Index);
}
for (int i = 0; i < indexes.Count; i++)
{
Console.WriteLine("{0}. match in index {1}", i+1, indexes[i]);
}
Output will be;
1. match in index: 3
2. match in index: 10
Here a DEMO.
Use String.Contains() for this purpose
if(ss.Contains("091"))
{
Console.WriteLine(" found");
}
if you want to know where "091" starts in the string then you can use:
var pos = ss.IndexOf("091")

Get all instances of sub-string one at a time?

If i have a string containing three 0 values, how would i grab them one by one in order to replace them?
the 0's could be located anywhere in the string.
i don't want to use regex.
example string to parse:
String myString = "hello 0 goodbye 0 clowns are cool 0";
right now i can only find the three 0 values if they are right next to each other. i replace them using stringToParse.Replace("0", "whatever value i want to replace it with");
I want to be able to replace each instance of 0 with a different value...
You can do something like this:
var strings = myString.Split('0');
var replaced = new StringBuilder(strings[0]);
for (var i = 1; i < strings.Length; ++i)
{
replaced.Append("REPLACED " + i.ToString());
replaced.Append(strings[i]);
}
pseudolang :
s = "yes 0 ok 0 and 0"
arr = s.split(" 0")
newstring = arr[0] + replace1 + arr[1] + replace2 + arr[2] + replace3
If you have control of these input strings, then I would use a composite format string instead:
string myString = "hello {0} goodbye {1} clowns are cool {2}";
string replaced = string.Format(myString, "replace0", "replace1", "replace2");
public string ReplaceOne(string full, string match, string replace)
{
int firstMatch = full.indexOf(match);
if(firstMatch < 0)
{
return full;
}
string left;
string right;
if(firstMatch == 0)
left = "";
else
left = full.substring(0,firstMatch);
if(firstMatch + match.length >= full.length)
right = "";
else
right = full.substring(firstMatch+match.length);
return left + replace + right
}
If your match can occur in replace, then you will want to track what index your upto and pass it in to indexOf.
Using LINQ and generic function to decouple replacement logic.
var replace = (index) => {
// put any custom logic here
return (char) index;
};
string input = "hello 0 goodbye 0 clowns are cool 0";
string output = new string(input.Select((c, i) => c == '0' ? replace(i) : c)
.ToArray());
Pros:
Char replacement logic decoupled from the string processing (actually LINQ query)
Cons:
Not the best solution from performance perspectives

Replace consecutive characters with same single character

I was just wondering if there is a simple way of doing this. i.e. Replacing the occurrence of consecutive characters with the same character.
For eg: - if my string is "something likeeeee tttthhiiissss" then my final output should be "something like this".
The string can contain special characters too including space.
Can you guys suggest some simple way for doing this.
This should do it:
var regex = new Regex("(.)\\1+");
var str = "something likeeeee!! tttthhiiissss";
Console.WriteLine(regex.Replace(str, "$1")); // something like! this
The regex will match any character (.) and \\1+ will match whatever was captured in the first group.
string myString = "something likeeeee tttthhiiissss";
char prevChar = '';
StringBuilder sb = new StringBuilder();
foreach (char chr in myString)
{
if (chr != prevChar) {
sb.Append(chr);
prevChar = chr;
}
}
How about:
s = new string(s
.Select((x, i) => new { x, i })
.Where(x => x.i == s.Length - 1 || s[x.i + 1] != x.x)
.Select(x => x.x)
.ToArray());
In english, we are creating a new string based on a char[] array. We construct that char[] array by applying a few LINQ operators:
Select: Capture the index i along with the current character x.
Filter out charaters that are not the same as the subsequent character
Select the character x.x back out of the anonymous type x.
Convert back to a char[] array so we can pass to constructor of string.
Console.WriteLine("Enter any string");
string str1, result="", str = Console.ReadLine();
char [] array= str.ToCharArray();
int i=0;
for (i = 0; i < str.Length;i++ )
{
if ((i != (str.Length - 1)))
{ if (array[i] == array[i + 1])
{
str1 = str.Trim(array[i]);
}
else
{
result += array[i];
}
}
else
{
result += array[i];
}
}
Console.WriteLine(result);
In this code the program ;
will read the string as entered from user
2.Convert the string in char Array using string.ToChar()
The loop will run for each character in string
each character stored in that particular position in array will be compared to the character stored in position one greater than that . And if the characters are found same the character stored in that particular array would be trimmed using .ToTrim()
For last character the loop will show error of index out of bound as it would be the last position value of the array. That's why I used * if ((i != (str.Length - 1)))*
6.The characters left after trimming are stored in result in concatenated form .
word = "something likeeeee tttthhiiissss"
re.sub(r"(.)\1+", r"\1",word)

Parse an integer from a string with trailing garbage

I need to parse a decimal integer that appears at the start of a string.
There may be trailing garbage following the decimal number. This needs to be ignored (even if it contains other numbers.)
e.g.
"1" => 1
" 42 " => 42
" 3 -.X.-" => 3
" 2 3 4 5" => 2
Is there a built-in method in the .NET framework to do this?
int.TryParse() is not suitable. It allows trailing spaces but not other trailing characters.
It would be quite easy to implement this but I would prefer to use the standard method if it exists.
You can use Linq to do this, no Regular Expressions needed:
public static int GetLeadingInt(string input)
{
return Int32.Parse(new string(input.Trim().TakeWhile(c => char.IsDigit(c) || c == '.').ToArray()));
}
This works for all your provided examples:
string[] tests = new string[] {
"1",
" 42 ",
" 3 -.X.-",
" 2 3 4 5"
};
foreach (string test in tests)
{
Console.WriteLine("Result: " + GetLeadingInt(test));
}
foreach (var m in Regex.Matches(" 3 - .x. 4", #"\d+"))
{
Console.WriteLine(m);
}
Updated per comments
Not sure why you don't like regular expressions, so I'll just post what I think is the shortest solution.
To get first int:
Match match = Regex.Match(" 3 - .x. - 4", #"\d+");
if (match.Success)
Console.WriteLine(int.Parse(match.Value));
There's no standard .NET method for doing this - although I wouldn't be surprised to find that VB had something in the Microsoft.VisualBasic assembly (which is shipped with .NET, so it's not an issue to use it even from C#).
Will the result always be non-negative (which would make things easier)?
To be honest, regular expressions are the easiest option here, but...
public static string RemoveCruftFromNumber(string text)
{
int end = 0;
// First move past leading spaces
while (end < text.Length && text[end] == ' ')
{
end++;
}
// Now move past digits
while (end < text.Length && char.IsDigit(text[end]))
{
end++;
}
return text.Substring(0, end);
}
Then you just need to call int.TryParse on the result of RemoveCruftFromNumber (don't forget that the integer may be too big to store in an int).
I like #Donut's approach.
I'd like to add though, that char.IsDigit and char.IsNumber also allow for some unicode characters which are digits in other languages and scripts (see here).
If you only want to check for the digits 0 to 9 you could use "0123456789".Contains(c).
Three example implementions:
To remove trailing non-digit characters:
var digits = new string(input.Trim().TakeWhile(c =>
("0123456789").Contains(c)
).ToArray());
To remove leading non-digit characters:
var digits = new string(input.Trim().SkipWhile(c =>
!("0123456789").Contains(c)
).ToArray());
To remove all non-digit characters:
var digits = new string(input.Trim().Where(c =>
("0123456789").Contains(c)
).ToArray());
And of course: int.Parse(digits) or int.TryParse(digits, out output)
This doesn't really answer your question (about a built-in C# method), but you could try chopping off characters at the end of the input string one by one until int.TryParse() accepts it as a valid number:
for (int p = input.Length; p > 0; p--)
{
int num;
if (int.TryParse(input.Substring(0, p), out num))
return num;
}
throw new Exception("Malformed integer: " + input);
Of course, this will be slow if input is very long.
ADDENDUM (March 2016)
This could be made faster by chopping off all non-digit/non-space characters on the right before attempting each parse:
for (int p = input.Length; p > 0; p--)
{
char ch;
do
{
ch = input[--p];
} while ((ch < '0' || ch > '9') && ch != ' ' && p > 0);
p++;
int num;
if (int.TryParse(input.Substring(0, p), out num))
return num;
}
throw new Exception("Malformed integer: " + input);
string s = " 3 -.X.-".Trim();
string collectedNumber = string.empty;
int i;
for (x = 0; x < s.length; x++)
{
if (int.TryParse(s[x], out i))
collectedNumber += s[x];
else
break; // not a number - that's it - get out.
}
if (int.TryParse(collectedNumber, out i))
Console.WriteLine(i);
else
Console.WriteLine("no number found");
This is how I would have done it in Java:
int parseLeadingInt(String input)
{
NumberFormat fmt = NumberFormat.getIntegerInstance();
fmt.setGroupingUsed(false);
return fmt.parse(input, new ParsePosition(0)).intValue();
}
I was hoping something similar would be possible in .NET.
This is the regex-based solution I am currently using:
int? parseLeadingInt(string input)
{
int result = 0;
Match match = Regex.Match(input, "^[ \t]*\\d+");
if (match.Success && int.TryParse(match.Value, out result))
{
return result;
}
return null;
}
Might as well add mine too.
string temp = " 3 .x£";
string numbersOnly = String.Empty;
int tempInt;
for (int i = 0; i < temp.Length; i++)
{
if (Int32.TryParse(Convert.ToString(temp[i]), out tempInt))
{
numbersOnly += temp[i];
}
}
Int32.TryParse(numbersOnly, out tempInt);
MessageBox.Show(tempInt.ToString());
The message box is just for testing purposes, just delete it once you verify the method is working.
I'm not sure why you would avoid Regex in this situation.
Here's a little hackery that you can adjust to your needs.
" 3 -.X.-".ToCharArray().FindInteger().ToList().ForEach(Console.WriteLine);
public static class CharArrayExtensions
{
public static IEnumerable<char> FindInteger(this IEnumerable<char> array)
{
foreach (var c in array)
{
if(char.IsNumber(c))
yield return c;
}
}
}
EDIT:
That's true about the incorrect result (and the maintenance dev :) ).
Here's a revision:
public static int FindFirstInteger(this IEnumerable<char> array)
{
bool foundInteger = false;
var ints = new List<char>();
foreach (var c in array)
{
if(char.IsNumber(c))
{
foundInteger = true;
ints.Add(c);
}
else
{
if(foundInteger)
{
break;
}
}
}
string s = string.Empty;
ints.ForEach(i => s += i.ToString());
return int.Parse(s);
}
private string GetInt(string s)
{
int i = 0;
s = s.Trim();
while (i<s.Length && char.IsDigit(s[i])) i++;
return s.Substring(0, i);
}
Similar to Donut's above but with a TryParse:
private static bool TryGetLeadingInt(string input, out int output)
{
var trimmedString = new string(input.Trim().TakeWhile(c => char.IsDigit(c) || c == '.').ToArray());
var canParse = int.TryParse( trimmedString, out output);
return canParse;
}

Categories