string reverse in C# - c#

For example, my input is my name is abcd
I need to display as dcba si eman ym
I have done below which is giving an output as abcd is name my
but have no idea what to do next
static void Main(string[] args)
{
Console.WriteLine("Enter a string: ");
string[] input = Console.ReadLine().Split(' ');
for (int i = input.Length-1; i >=0; i--)
{
Console.Write(input[i]+" ");
}
Console.ReadKey();
}

You can use the API - Array.Reverse
char[] charArray = input.ToCharArray();
Array.Reverse( charArray );
reversed = new string( charArray );

Try this this will work perfectly. I think this is what you have been looking for!
string Str, reversestring = "";
int Length;
Console.Write("Enter A String : ");
Str = Console.ReadLine();
Length = Str.Length - 1;
while (Length >= 0)
{
reversestring = reversestring + Str[Length];
Length--;
}
Console.WriteLine("Reverse String Is {0}", reversestring);
Console.ReadLine();
My Fiddle example: Reverse with Words and Text

You don't need the .Split(' ') in string[] input = Console.ReadLine().Split(' ');
You can simply read the entire line with string input = Console.ReadLine(); then reverse the entire line.
If you look at the below link it provides two options.
Reverse the entire string using a Array.Reverse
loop through every character from the end to the start and output it.
https://www.dotnetperls.com/reverse-string#d

What your code do is reversing the initial string by words, like this:
my name is abcd --> abcd is name my
To change this you need to read the whole string and use it as char array:
var input = Console.ReadLine();
var sb = new StringBuilder(input.Length);
for (var i = input.Length - 1; i >= 0; --i)
{
sb.Append(input[i]);
}
Console.WriteLine(sb.ToString());
Also you can use the Array.Reverse method:
var input = Console.ReadLine();
var charArray = input.ToCharArray();
Array.Reverse(charArray);
var reversed = new string(charArray);
Console.WriteLine(reversed);

You can use LINQ's Aggregate function to reverse a string
Console.WriteLine("Enter a string: ");
string input = Console.ReadLine();
input = input.Aggregate(new StringBuilder(), (j, k) => j.Insert(0, k)).ToString();
The Aggregate prepend each Char to the reversed string

public static string RevString(string str)
{
var charArry = str.ToCharArray();
Array.Reverse(charArry);
return new string(charArry);
}
public static string RevString2(string str)
{
string revString = "";
foreach( char c in str)
{
revString = c + revString;
}
return revString;
}
//no change to the order of the words
public static string RevString3(string str)
{
string[] strArray = str.Split(' ');
string revString = "";
foreach (string s in strArray)
{
var charArray = s.ToCharArray();
Array.Reverse(charArray);
revString += new string(charArray) + " ";
}
return revString;
}
public static string RevString4(string str)
{
string[] strArray = str.Split(' ');
string revString = "";
foreach (string s in strArray)
{
string revWord = "";
foreach(char c in s)
{
revWord = c + revWord;
}
revString += revWord + " ";
}
return revString;
}

Related

Attach every last letter of the word with the next word in C#

There is an interview question that asks me to attach every last letter of the word with the next word in C#. For example the input is "Hey hello world" and the output should be "He yhell oworld".
I've come up with the code below but is there a better way to do this? Perhaps in LINQ?
string inputString = "Hey Hello World";
string[] stringArray = inputString.Split(' ').ToArray();
StringBuilder resultString = new StringBuilder("");
StringBuilder lastLetter = new StringBuilder("");
for (int i = 0; i < stringArray.Length; i++)
{
string temp = stringArray[i].ToString();
if (i < stringArray.Length - 2)
{
resultString.Append(lastLetter + temp.Substring(0, temp.Length - 1));
lastLetter.Clear();
lastLetter.Append(" " + temp.Substring(temp.Length - 1, 1));
}
else
resultString.Append(lastLetter + temp.Substring(0, temp.Length));
}
Console.WriteLine(resultString);
How about using regex
var newtext = Regex.Replace("Hey hello world", #"(.) "," $1");
You are unnecessarily complicating the code. Simply replace space with previous character.
var input = "Hey Hello world";
var arr = input.Trim().ToCharArray();
for(int i =0; i< arr.Length; i++)
{
if(arr[i]==' ')
{
var temp = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = temp;
}
}
Console.WriteLine(arr);
Here's a LINQ solution, since that seems to be what the OP is looking for.
using System;
using System.Linq;
public class Program
{
const char space = ' ';
public static string DoHomework(string input)
{
return new string
(
input.Select( (c,i) =>
{
if (i == 0 || i == input.Length-1) return c;
if (c == space) return input[i-1];
if (input[i+1] == space) return space;
return c;
}).ToArray()
);
}
public static void Main()
{
var input = "Hey hello world";
var output = DoHomework(input);
Console.WriteLine(output);
}
}
Output:
He yhell oworld
Try it out on DotNetFiddle

Using indexOf (C#) to remove a set of characters from a string

public static string shita1(string st1)
{
string st2 = "", stemp = st1;
int i;
for(i=0; i<stemp.Length; i++)
{
if (stemp.IndexOf("cbc") == i)
{
i += 2 ;
stemp = "";
stemp = st1.Substring(i);
i = 0;
}
else
st2 = st2 + stemp[i];
}
return st2;
}
static void Main(string[] args)
{
string st1;
Console.WriteLine("enter one string:");
st1 = Console.ReadLine();
Console.WriteLine(shita1(st1));
}
}
i got a challange from my college, the challange is to move any "cbc" characters from a string...
this is my code... it works when i use only one "cbc" but when i use 2 of them it stucks... help please :)
The IndexOf Method gives you everything you need to know.
Per the documentation.
Reports the zero-based index of the first occurrence of a specified
Unicode character or string within this instance. The method returns
-1 if the character or string is not found in this instance.
This means you can create a loop that repeats as long as the returned index is not -1 and you don't have to loop through the string testing letter by letter.
I think this should work just tested it on some examples. Doesn't use string.Replace or IndexOf
static void Main(string[] args)
{
Console.WriteLine("enter one string:");
var input = Console.ReadLine();
Console.WriteLine(RemoveCBC(input));
}
static string RemoveCBC(string source)
{
var result = new StringBuilder();
for (int i = 0; i < source.Length; i++)
{
if (i + 2 == source.Length)
break;
var c = source[i];
var b = source[i + 1];
var c2 = source[i + 2];
if (c == 'c' && c2 == 'c' && b == 'b')
i = i + 2;
else
result.Append(source[i]);
}
return result.ToString();
}
You can use Replace to remove/replace all occurances of a string inside another string:
string original = "cbc_STRING_cbc";
original = original.Replace("cbc", String.Empty);
If you want remove characters from string using only IndexOf method you can use this code.
public static string shita1(string st1)
{
int index = -1;
string yourMatchingString = "cbc";
while ((index = st1.IndexOf(yourMatchingString)) != -1)
st1 = st1.Remove(index, yourMatchingString.Length);
return st1;
}
This code remove all inputs of you string.
But you can do it just in one line:
st1 = st1.Replace("cbc", string.Empty);
Hope this help.

String Reverse : reversing only position of the Words in String in c#

original String is "Hello World"
Output Should be "World Hello"
What is the optimized way to do it in c# ?
Please suggest me any existing link if i am missing
var s = "Hello world";
var result = String.Join(" ", s.Split(' ').Reverse()));
OR (better split below if you ar not sure of your data)
var s = "Hello world";
var result = String.Join(" ", Regex.Split(s, #"\s").Reverse());
I would split the sentence by the words (the space between them):
string[] words = helloString.Split(" ");
helloString = words[1] + " " + words[0];
You could optimise this to work with any sentence with any number of words by looping through words from the last element to the first.
I've reassigned the new string back to helloString (the original) as I assume this is what you want based on the question.
Try This Code :
string value = "Hello world";
string firstvalue = value.Split(' ').First();
string secvalue = value.Split(' ').Last();
string value = secvalue + firstvalue;
static void Main(string[] args)
{
String str = "Hello World";
String[] strNames = str.Split(' ');
for(int i=strNames.Length-1;i>=0;i--)
Console.Write(strNames[i]+" ");
}
char[] Delimiter = new char[] { ' ' }
string[] t = string.split("Hello Wordl", Delimiter)
int lenS = t.Count;
string result = "";
for(int x =t-1; t > -1; t--)
{
result += t[x] + " ";
}
//Used result now

How can I delete the first n lines in a string in C#?

How can I delete the first n lines in a string?
Example:
String str = #"a
b
c
d
e";
String output = DeleteLines(str, 2)
//Output is "c
//d
//e"
You can use LINQ:
String str = #"a
b
c
d
e";
int n = 2;
string[] lines = str
.Split(Environment.NewLine.ToCharArray())
.Skip(n)
.ToArray();
string output = string.Join(Environment.NewLine, lines);
// Output is
// "c
// d
// e"
If you need to take into account "\r\n" and "\r" and "\n" it's better to use the following regex:
public static class StringExtensions
{
public static string RemoveFirstLines(string text, int linesCount)
{
var lines = Regex.Split(text, "\r\n|\r|\n").Skip(linesCount);
return string.Join(Environment.NewLine, lines.ToArray());
}
}
Here are some more details about splitting text into lines.
Combination of Get the index of the nth occurrence of a string? (search for Environment.NewLine) and substring should do the trick.
Try the following:
public static string DeleteLines(string s, int linesToRemove)
{
return s.Split(Environment.NewLine.ToCharArray(),
linesToRemove + 1
).Skip(linesToRemove)
.FirstOrDefault();
}
the next example:
string str = #"a
b
c
d
e";
string output = DeleteLines(str, 2);
returns
c
d
e
Try this:
public static string DeleteLines (string text, int lineCount) {
while (text.Split('\n').Length > lineCount)
text = text.Remove(0, text.Split('\n')[0].Length + 1);
return text;
}
It might not be very efficient but it works perfectly for the little project i've been working on recently
Try the following:
private static string DeleteLines(string input, int lines)
{
var result = input;
for(var i = 0; i < lines; i++)
{
var idx = result.IndexOf('\n');
if (idx < 0)
{
// do what you want when there are less than the required lines
return string.Empty;
}
result = result.Substring(idx+1);
}
return result;
}
Note: This method is not ideal for extremely long multi-line strings as it does not consider memory management. If dealing with these kind of strings, I suggest you alter the method to use the StringBuilder class.
With ability to delete first n lines or last n lines:
public static string DeleteLines(
string stringToRemoveLinesFrom,
int numberOfLinesToRemove,
bool startFromBottom = false) {
string toReturn = "";
string[] allLines = stringToRemoveLinesFrom.Split(
separator: Environment.NewLine.ToCharArray(),
options: StringSplitOptions.RemoveEmptyEntries);
if (startFromBottom)
toReturn = String.Join(Environment.NewLine, allLines.Take(allLines.Length - numberOfLinesToRemove));
else
toReturn = String.Join(Environment.NewLine, allLines.Skip(numberOfLinesToRemove));
return toReturn;
}
public static string DeleteLines(string input, int linesToSkip)
{
int startIndex = 0;
for (int i = 0; i < linesToSkip; ++i)
startIndex = input.IndexOf('\n', startIndex) + 1;
return input.Substring(startIndex);
}

How can you remove duplicate characters in a string?

I have to implements a function that takes a string as an input and finds the non-duplicate character from this string.
So an an example is if I pass string str = "DHCD" it will return "DHC"
or str2 = "KLKLHHMO" it will return "KLHMO"
A Linq approach:
public static string RemoveDuplicates(string input)
{
return new string(input.ToCharArray().Distinct().ToArray());
}
It will do the job
string removedupes(string s)
{
string newString = string.Empty;
List<char> found = new List<char>();
foreach(char c in s)
{
if(found.Contains(c))
continue;
newString+=c.ToString();
found.Add(c);
}
return newString;
}
I should note this is criminally inefficient.
I think I was delirious on first revision.
For arbitrary length strings of byte-sized characters (not for wide characters or other encodings), I would use a lookup table, one bit per character (32 bytes for a 256-bit table). Loop through your string, only output characters that don't have their bits turned on, then turn the bit on for that character.
string removedupes(string s)
{
string t;
byte[] found = new byte[256];
foreach(char c in s)
{
if(!found[c]) {
t.Append(c);
found[c]=1;
}
}
return t;
}
I am not good with C#, so I don't know the right way to use a bitfield instead of a byte array.
If you know that your strings are going to be very short, then other approaches would offer better memory usage and/or speed.
void removeDuplicate()
{
string value1 = RemoveDuplicateChars("Devarajan");
}
static string RemoveDuplicateChars(string key)
{
string result = "";
foreach (char value in key)
if (result.IndexOf(value) == -1)
result += value;
return result;
}
It sounds like homework to me, so I'm just going to describe at a high level.
Loop over the string, examining each character
Check if you've seen the character before
if you have, remove it from the string
if you haven't, note that you've now seen that character
this is in C#. validation left out for brevity. primitive solution for removing duplicate chars from a given string
public static char[] RemoveDup(string s)
{
char[] chars = new char[s.Length];
int unique = 0;
chars[unique] = s[0]; // Assume: First char is unique
for (int i = 1; i < s.Length; i++)
{
// add char in i index to unique array
// if char in i-1 != i index
// i.e s = "ab" -> a != b
if (s[i-1] != s[i]
chars[++unique] = s[i];
}
return chars;
}
My answer in java language.
Posting here so that you might get a idea even it is in Java language.Algorithm would remain same.
public String removeDup(String s)
{
if(s==null) return null;
int l = s.length();
//if length is less than 2 return string
if(l<2)return s;
char arr[] = s.toCharArray();
for(int i=0;i<l;i++)
{
int j =i+1; //index to check with ith index
int t = i+1; //index of first repetative char.
while(j<l)
{
if(arr[j]==arr[i])
{
j++;
}
else
{
arr[t]=arr[j];
t++;
j++;
}
}
l=t;
}
return new String(arr,0,l);
}
you may use HashSet:
static void Main()
{
string textWithDuplicates = "aaabbcccggg";
Console.WriteLine(textWithDuplicates.Count());
var letters = new HashSet<char>(textWithDuplicates);
Console.WriteLine(letters.Count());
foreach (char c in letters) Console.Write(c);
}
class Program
{
static void Main(string[] args)
{
bool[] doesExists = new bool[256];
String st = Console.ReadLine();
StringBuilder sb = new StringBuilder();
foreach (char ch in st)
{
if (!doesExists[ch])
{
sb.Append(ch);
doesExists[ch] = true;
}
}
Console.WriteLine(sb.ToString());
}
}
Revised version of the first answer i.e: You don't need ToCharArray() function for this to work.
public static string RemoveDuplicates(string input)
{
return new string(input.Distinct().ToArray());
}
char *remove_duplicates(char *str)
{
char *str1, *str2;
if(!str)
return str;
str1 = str2 = str;
while(*str2)
{
if(strchr(str, *str2)<str2)
{
str2++;
continue;
}
*str1++ = *str2++;
}
*str1 = '\0';
return str;
}
char* removeDups(const char* str)
{
char* new_str = (char*)malloc(256*sizeof(char));
int i,j,current_pos = 0,len_of_new_str;
new_str[0]='\0';
for(i=0;i<strlen(str);i++)
{
len_of_new_str = strlen(new_str);
for(j=0;j<len_of_new_str && new_str[j]!=str[i];j++)
;
if(j==len_of_new_str)
{
new_str[len_of_new_str] = str[i];
new_str[len_of_new_str+1] = '\0';
}
}
return new_str;
}
Hope this helps
String str="AABBCANCDE";
String newStr="";
for( int i=0; i<str.length(); i++)
{
if(!newStr.contains(str.charAt(i)+""))
newStr= newStr+str.charAt(i);
}
System.out.println(newStr);
// Remove both upper-lower duplicates
public static string RemoveDuplicates(string key)
{
string Result = string.Empty;
foreach (char a in key)
{
if (Result.Contains(a.ToString().ToUpper()) || Result.Contains(a.ToString().ToLower()))
continue;
Result += a.ToString();
}
return Result;
}
var input1 = Console.ReadLine().ToLower().ToCharArray();
var input2 = input1;
var WithoutDuplicate = input1.Union(input2);
Console.WriteLine("Enter String");
string str = Console.ReadLine();
string result = "";
result += str[0]; // first character of string
for (int i = 1; i < str.Length; i++)
{
if (str[i - 1] != str[i])
result += str[i];
}
Console.WriteLine(result);
I like Quintin Robinson answer, only there should be some improvements like removing List, because it is not necessarry in this case.
Also, in my opinion Uppercase char ("K") and lowercase char ("k") is the same thing, so they should be counted as one.
So here is how I would do it:
private static string RemoveDuplicates(string textEntered)
{
string newString = string.Empty;
foreach (var c in textEntered)
{
if (newString.Contains(char.ToLower(c)) || newString.Contains(char.ToUpper(c)))
{
continue;
}
newString += c.ToString();
}
return newString;
}
Not sure how optimal it is:
public static string RemoveDuplicates(string input)
{
var output = string.Join("", input.ToHashSet());
return output;
}
Below is the code to remove duplicate chars from a string
var input = "SaaSingeshe";
var filteredString = new StringBuilder();
foreach(char c in input)
{
if(filteredString.ToString().IndexOf(c)==-1)
{
filteredString.Append(c);
}
}
Console.WriteLine(filteredString);
Console.ReadKey();
namespace Demo { class Program {
static void Main(string[] args) {
string myStr = "kkllmmnnouo";
Console.WriteLine("Initial String: "+myStr);
// var unique = new HashSet<char>(myStr);
HashSet<char> unique = new HashSet<char>(myStr);
Console.Write("New String after removing duplicates: ");
foreach (char c in unique)
Console.Write(c);
} } }
this works for me
private string removeDuplicateChars(String value)
{
return new string(value.Distinct().ToArray());
}

Categories