Split String in C# without delimiter (sort of) - c#

I want to split a string in C#.NET that looks like this:
string Letters = "hello";
and put each letter (h, e, l, l, o) into an array or ArrayList. I have no idea what to use as the delimiter in String.Split(delimiter). I can do it if the original string has commas (or anything else):
string Letters = "H,e,l,l,o";
string[] AllLettersArray = Letters.Split(",".ToCharArray());
But I have no idea what to use in a case with (supposedly) no delimiter. Is there a special character like Environment.Newline? Thanks.

Remember, you can access a string as an array in c#.
string str = "hello";
char[] letters = str.ToCharArray();

Here is another full solution that uses a loop. This takes a regular string "helloworld" and puts each character into an array as a string. The most straightforward method without using LINQ or other references.
string str = "helloworld";
string[] arr = new string[str.Length];
for(int i=0; i<str.Length; i++)
{
arr[i] = str[i].ToString();
}
This can be added to your codebase as an extension method.
public static class StringExtensions
{
public static string[] ToStringArray(this string str)
{
string[] arr = new string[str.Length];
for(int i=0; i<str.Length; i++)
{
arr[i] = str[i].ToString();
}
return arr;
}
}
And then you have a 1 liner for the conversion.
string str = "helloworld";
string[] arr = str.ToStringArray();

Related

Index was outside the bounds of the array in my case

Why the index in my case goes beyond the boundaries of the array, I still can't understand?
Complete the method/function so that it converts dash/underscore delimited words into camel casing. The first word within the output should be capitalized only if the original word was capitalized (known as Upper Camel Case, also often referred to as Pascal case).
using System;
using System.Text;
public class Kata
{
public static string ToCamelCase(string str)
{
string[] res=str.Split(new char[]{'-','_'},System.StringSplitOptions.RemoveEmptyEntries);
StringBuilder sb=new StringBuilder(res[0]);
for(int i=1;i<res.Length;i++){
char[] ch=res[i].ToCharArray();
ch[0]=Char.ToUpper(ch[0]);
sb.Append(new string(ch));
}
return sb.ToString();
}
}
#Evgeny20 First, you should do your own homework. Second, debuggers are your friend, whatever environment they have you using for your CS homework figure out the debugger so you can step through it. This type of thing becomes easy then.
I'll provide a solution that's using .net core 3.1. If you're using old framework you'll need to modify it to not use Spans and instead use string functions. Don't use the char array.
If you get array index out of bound issues with this - using the forced upper case - then then put in a test for the string to make sure it's non-null and non-empty. But I don't think you will...
static async Task Main(string[] args)
{
const string S1 = "camel-Case_this-String";
const string Check = "camelCaseThisString";
var result = ToCamelCase(S1);
if (result != Check)
throw new InvalidOperationException();
}
public static string ToCamelCase(string str)
{
if (string.IsNullOrEmpty(str))
return str;
string[] tokens = str.Split(new char[] { '-', '_' }, StringSplitOptions.RemoveEmptyEntries);
if (tokens.Length == 0)
return str;
StringBuilder sb = new StringBuilder(str.Length);
sb.Append(tokens.First());
foreach (var token in tokens.Skip(1))
{
sb.Append(char.ToUpper(token[0]));
if (token.Length > 1)
{
sb.Append(token.AsSpan().Slice(1));
}
}
return sb.ToString();
}
I'm offering two solutions. The first formats the input as Pascal Case.
static void Main(string[] args)
{
Console.WriteLine(ToCamelCase("camels-drink-LOTS-OF_WATER"));
Console.ReadKey();
}
public static string ToCamelCase(string str)
{
// This holds our output
StringBuilder sb = new StringBuilder();
// Step 1 - split input into array of words
string[] res = str.Split(new char[] { '-', '_' }, System.StringSplitOptions.RemoveEmptyEntries);
// Step 2 - loop through the array
for (int i = 0; i < res.Length; i++)
{
// For each word,
// change all of the letters to lowercase
res[i] = res[i].ToLower();
// Then change the first letter to uppercase
char[] ch = res[i].ToCharArray();
ch[0] = Char.ToUpper(ch[0]);
// Finally, add the result to our output
string c = new string(ch);
sb.Append(c);
}
return sb.ToString();
}
The second formats as Camel Case - it contains additional logic to handle the first word in your input array.
static void Main(string[] args)
{
Console.WriteLine(ToCamelCase("camels-drink-LOTS-OF_WATER"));
Console.ReadKey();
}
public static string ToCamelCase(string str)
{
// This holds our output
StringBuilder sb = new StringBuilder();
// Step 1 - split input into array of words
string[] res = str.Split(new char[] { '-', '_' }, System.StringSplitOptions.RemoveEmptyEntries);
// Step 2 - loop through the array
for (int i = 0; i < res.Length; i++)
{
// For each word,
// change all of the letters to lowercase
res[i] = res[i].ToLower();
// Then change the first letter to uppercase unless it's the first word
char[] ch = res[i].ToCharArray();
if (i != 0)
{
ch[0] = Char.ToUpper(ch[0]);
}
// Finally, add the result to our output
string c = new string(ch);
sb.Append(c);
}
return sb.ToString();
}
Let me know in the comments if you need any more help.
If this answer helps you, please click the gray checkmark to the left. This marks the question as solved and gives me some "rep" which is used to access features on Stack Overflow.

Can't reverse a string using a for loop

I need to reverse a string using a for loop but I just can't do it. What I'm doing wrong?
class Program
{
static void Main(string[] args)
{
string s;
string sReverse;
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
for (int i = 0; i < s.Length; i++)
{
s[s.Length - i] = sReversa[i];
}
}
}
Strings are immutable. You can't change them character by character.
If you want random access to the characters in a string, convert it to a char array first (using ToCharArray), then convert it back when you're done (String has a constructor that accepts a char array).
string a = "1234";
char[] b = a.ToCharArray();
b[1] = 'X';
a = new string(b);
Console.WriteLine("{0}", a);
Output:
1X34
There are much easier ways to reverse a string (e.g. LINQ would let you do var output = new string(input.Reverse().ToArray());), but if you want to use a for loop and your current approach, this is probably the piece of information you are missing.
These will be the minimal changes required in your code:
public static void Main()
{
string s;
string sReverse = string.Empty; // Initialise (always recommended)
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0 ; i--) // Chnage the order of indexing
{
sReverse += s[i]; // makes a new string everytime since strings are immutable.
}
Console.WriteLine(sReverse); // print your new string
}
As others said this may not be the best approach for very large number of string manipulation / formation. Instead, use StringBuilder.
StringBuilder is suited in situations where you need to perform repeated modifications to a string, the overhead associated with
creating a new String object can be costly.
Below is the snippet on how to use StringBuilder:
using System;
using System.Text; // Add this for StringBuilder
public class Program
{
public static void Main()
{
string s;
StringBuilder sReverse = new StringBuilder(); // Instantiate the object.
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
for (int i = s.Length-1; i >=0 ; i--)
{
sReverse.Append(s[i]); // Keep Appending to original string.
}
Console.WriteLine(sReverse.ToString()); // finally convert to printable string.
}
}
string reverse = string.Join("", "some word".Reverse());
You can not use s[s.Length - i] = sReversa[i];
Because Strings are immutable.
Instead, you can use sReverse = sReverse + s[Length];
The following code will give you reverse of a string:
static void Main(string[] args)
{
string s;
string sReverse = "";
int Length;
Console.WriteLine("Say any word please: ");
s = Console.ReadLine();
Length = s.Length - 1;
for (int i = Length; i >= 0; i--)
{
sReverse = sReverse + s[Length];
Length--;
}
Console.WriteLine("{0}", sReverse);
Console.ReadLine();
}
Note: For a large number of iteration, this might be a performance issue.
The simplest way to make your code work with minimal changes is to use a StringBuilder. Unlike string a StringBuilder is mutable.
Here's the code:
Console.WriteLine("Say any word please: ");
string s = Console.ReadLine();
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < s.Length; i++)
{
sb[s.Length - i - 1] = s[i];
}
string r = sb.ToString();
If you must use a for loop the way you want, you will have to allocate a new char array, initialize it with the string's characters from back to front, then take advantage of the string constructor that takes a char array as input. The code looks as follows:
public static string ReverseWithFor(string s)
{
if (string.IsNullOrEmpty(s)) return s;
char[] a = new char[s.Length];
for (int i = 0; i < s.Length; i++)
a[s.Length - 1 - i] = s[i];
return new string(a);
}

Concatenate multiple string using string interpolation in c#

The code I tried:
public void ConcatIntegers() {
string s = "";
for (int i = 0; i <= 5; i++) {
s += i.ToString();
}
Console.WriteLine($ "{s}");
Console.Read();
}
In Above method + is used to concatenate multiple values but I was looking for anyway except join, aggregate, concatenate function, instead of + symbol I want to use string interpolation ($) directly which store concatenated string into a string variable.
string s = "";
for (int i = 0; i <= 5; i++) {
// Some code which use string interpolation to
// concatenat multiple string and that result is stored in s
// variable.
}
Console.WriteLine($ "{s}");
Console.Read();
except join, aggregate, concatenate function, instead of + symbol I want to use string interpolation ($)
directly which store concatenated string into a string variable...
simply try:
string result = string.Empty;
for (var i = 0; i <= 5; i++) result = $"{result}{i}";
Use StringBuilder since if you do that a lot it is much faster
Use AppendFormat
StringBuilder sb = new StringBuilder();
string var1 = "abcd";
string var2 = "efgh";
sb.AppendFormat("example: {0}, {1}", var1, var2);
I would use String Builder to concatenate the string:
Your code after changes:
StringBuilder sb = new StringBuilder();
string s = "";
sb.Append(s);
for (int i = 0; i <= 5; i++)
{
sb.Append(i);
}
Console.WriteLine(sb);
Console.ReadLine();
If you want to concatenate, let's try string.Concat or string.Join; with a little help of Linq (in order to get rid of for loop) we'll get
using System.Linq;
...
// static: we don't use "this" in the method
public static void ConcatIntegers() {
// Concatenate range of 0..5 integers: "012345"
Console.WriteLine(string.Concat(Enumerable
.Range(0, 6))); // 6 - we want 6 numbers: 0..5
Console.Read();
}
In case you want to use some format, string interpolation etc. add Select:
public static void ConcatIntegers() {
// "000102030405" since we apply "d2" format (each number reprsented with 2 digits)
Console.WriteLine(string.Concat(Enumerable
.Range(0, 6)
.Select(i => $"{i:d2}"))); // each item in 2 digits format
Console.Read();
}
I had a similar issue on using string interpolation in string.join
string type1 = "a,b,c";
string[] type2 = new string[3] { "a", "b", "c" };
string result = string.Join(",", $"'{x}'");
In both cases, the output should be 'a','b','c'
how to use string.Join() with string interpolation for array of strings

How would you go about removing whitespace from a string without the use of methods such as .trim or .replace?

I'm also not allowed to use lists.
My initial thought process for this was to take the initial string then to turn that into a char array. Then after copy everything that is not a space to a second char array. Then convert that char array back to a string.
So quickly it would look something like this;
char[] firstArray;
char[] secondArray;
string someString;
for (int i = 0; i < someString.Length; i++)
{
firstArray = someString.ToCharArray();
secondArray = new char[someString.Length];
for (int j = 0; j < firstArray.Length; j++)
{
if (firstArray[j] != ' ')
{
secondArray[j] = firstArray[j];
}
}
someString = secondArray.ToString();
}
But when I initialise the second char array it would contain an extra char with no value if there was a space in it initially, since it was initialised to the same size as the first char array. Would I have to do a similar loop before just to count the amount of non-spaces then initialise secondArray based off that or is there a much simpler way than all of this that I am missing? (Without the use of .trim, .replace(or anything like them) or lists)
Any help would be appreciated.
A String already implements IEnumerable<char>, so no need to turn it into an array to begin with. You can enumerate it directly and remove whitespace chars. E.g:
string x = " Hello, world";
string trimmed = new String(x.Where(c => !Char.IsWhiteSpace(c)).ToArray());
Your code re-creates the firstArray array every time. And I'm not sure what the inner loop is for. Your code fixed:
char[] firstArray;
char[] secondArray;
string someString = "Blah blah blah";
firstArray = someString.ToCharArray();
secondArray = new char[someString.Length];
int newLength = 0;
for (int i = 0; i < firstArray.Length; i++) {
if (firstArray[i] != ' ') {
secondArray[newLength++] = firstArray[i];
}
}
someString = new string(secondArray, 0, newLength);
Another way using StringBuilder:
string someString = "Blah blah blah";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach(char c in someString) {
if (!Char.IsWhiteSpace(c)) {
sb.Append(c);
}
}
someString = sb.ToString();

How to compare string with another string using c#

I have a situation where i don't want to compare total string length to other string .
Example:
string MainString = "Deanna Ecker";
string SearchString = "Ecker Designs";
int value = MainString.IndexOf(SearchString);
here it is searching with whole string. but i need to find any word in MainString. not with whole string..
Let me know how is this possible.
If case-sensitivity is not an issue, you could split both strings by the space, then intersect the two lists to see if there are any matches:
var foundWords = MainString.Split(' ').Intersect(SearchString.Split(' '));
Or if you only want to know if a word was found:
var isMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();
you can convert your string to a char array then search each character via looping from all characters
such that
public bool MatchString(string first,string second)
{
char[] ch1=first.ToCharArray();
char[] ch2=second.ToCharArray();
bool match=false;
for(int i=0 ; i<ch1.length ; i++)
{
for(int j=0 ; j<ch2.length ; j++)
{
if(ch2[j]==ch[i])
{
match=true;
break;
}
}
}
return match;
}
Try: var wordMatch = MainString.Split(' ').Intersect(SearchString.Split(' ')).Any();

Categories