How to separate character and number part from string - c#

E.g., I would like to separate:
OS234 to OS and 234
AA4230 to AA and 4230
I have used following trivial solution, but I am quite sure that there should be a more efficient and robust solution .
private void demo()
{ string cell="ABCD4321";
int a = getIndexofNumber(cell);
string Numberpart = cell.Substring(a, cell.Length - a);
row = Convert.ToInt32(rowpart);
string Stringpart = cell.Substring(0, a);
}
private int getIndexofNumber(string cell)
{
int a = -1, indexofNum = 10000;
a = cell.IndexOf("0"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("1"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("2"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("3"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("4"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("5"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("6"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("7"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("8"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
a = cell.IndexOf("9"); if (a > -1) { if (indexofNum > a) { indexofNum = a; } }
if (indexofNum != 10000)
{ return indexofNum; }
else
{ return 0; }
}

Regular Expressions are best suited for this kind of work:
using System.Text.RegularExpressions;
Regex re = new Regex(#"([a-zA-Z]+)(\d+)");
Match result = re.Match(input);
string alphaPart = result.Groups[1].Value;
string numberPart = result.Groups[2].Value;

Use Linq to do this
string str = "OS234";
var digits = from c in str
select c
where Char.IsDigit(c);
var alphas = from c in str
select c
where !Char.IsDigit(c);

Everyone and their mother will give you a solution using regex, so here's one that is not:
// s is string of form ([A-Za-z])*([0-9])* ; char added
int index = s.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });
string chars = s.Substring(0, index);
int num = Int32.Parse(s.Substring(index));

I really like jason's answer. Lets improve it a bit. We dont need regex here. My solution handle input like "H1N1":
public static IEnumerable<string> SplitAlpha(string input)
{
var words = new List<string> { string.Empty };
for (var i = 0; i < input.Length; i++)
{
words[words.Count-1] += input[i];
if (i + 1 < input.Length && char.IsLetter(input[i]) != char.IsLetter(input[i + 1]))
{
words.Add(string.Empty);
}
}
return words;
}
This solution is linear O(n).
output
"H1N1" -> ["H", "1", "N", "1"]
"H" -> ["H"]
"GH1N12" -> ["GH", "1", "N", "12"]
"OS234" -> ["OS", "234"]
Same solution with a StringBuilder
public static IEnumerable<string> SplitAlpha(string input)
{
var words = new List<StringBuilder>{new StringBuilder()};
for (var i = 0; i < input.Length; i++)
{
words[words.Count - 1].Append(input[i]);
if (i + 1 < input.Length && char.IsLetter(input[i]) != char.IsLetter(input[i + 1]))
{
words.Add(new StringBuilder());
}
}
return words.Select(x => x.ToString());
}
Try it Online!

If you want resolve more occurrences of char followed by number or vice versa you can use
private string SplitCharsAndNums(string text)
{
var sb = new StringBuilder();
for (var i = 0; i < text.Length - 1; i++)
{
if ((char.IsLetter(text[i]) && char.IsDigit(text[i+1])) ||
(char.IsDigit(text[i]) && char.IsLetter(text[i+1])))
{
sb.Append(text[i]);
sb.Append(" ");
}
else
{
sb.Append(text[i]);
}
}
sb.Append(text[text.Length-1]);
return sb.ToString();
}
And then
var text = SplitCharsAndNums("asd1 asas4gr5 6ssfd");
var tokens = text.Split(' ');

Are you doing this for sorting purposes? If so, keep in mind that Regex can kill performance for large lists. I frequently use an AlphanumComparer that's a general solution to this problem (can handle any sequence of letters and numbers in any order). I believe that I adapted it from this page.
Even if you're not sorting on it, using the character-by-character approach (if you have variable lengths) or simple substring/parse (if they're fixed) will be a lot more efficient and easier to test than a Regex.

I have used bniwredyc's answer to get Improved version of my routine:
private void demo()
{
string cell = "ABCD4321";
int row, a = getIndexofNumber(cell);
string Numberpart = cell.Substring(a, cell.Length - a);
row = Convert.ToInt32(Numberpart);
string Stringpart = cell.Substring(0, a);
}
private int getIndexofNumber(string cell)
{
int indexofNum=-1;
foreach (char c in cell)
{
indexofNum++;
if (Char.IsDigit(c))
{
return indexofNum;
}
}
return indexofNum;
}

.NET 2.0 compatible, without regex
public class Result
{
private string _StringPart;
public string StringPart
{
get { return _StringPart; }
}
private int _IntPart;
public int IntPart
{
get { return _IntPart; }
}
public Result(string stringPart, int intPart)
{
_StringPart = stringPart;
_IntPart = intPart;
}
}
class Program
{
public static Result GetResult(string source)
{
string stringPart = String.Empty;
int intPart;
var buffer = new StringBuilder();
foreach (char c in source)
{
if (Char.IsDigit(c))
{
if (stringPart == String.Empty)
{
stringPart = buffer.ToString();
buffer.Remove(0, buffer.Length);
}
}
buffer.Append(c);
}
if (!int.TryParse(buffer.ToString(), out intPart))
{
return null;
}
return new Result(stringPart, intPart);
}
static void Main(string[] args)
{
Result result = GetResult("OS234");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
result = GetResult("AA4230 ");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
result = GetResult("ABCD4321");
Console.WriteLine("String part: {0} int part: {1}", result.StringPart, result.IntPart);
Console.ReadKey();
}
}

Just use the substring function and set position inside the bracket.
String id = "DON123";
System.out.println("Id nubmer is : "+id.substring(3,6));
Answer:
Id number is: 123

use Split to seprate string from sting that use tab \t and space
string s = "sometext\tsometext\tsometext";
string[] split = s.Split('\t');
now you have an array of string that you want too easy

Related

How to find number of specific strings in a string in c#

There is a string: xxoxoxoxoxoxooxxxxox where x is a seat that is occupied and o is not, I have to find individual occupied seats, with both sides having an x.
I tried to look at
for (int i = 0; i < string.Length; i++) {
if(string[i]=='x' && string[i + 1]=='o' && string[i + 2] == 'x')
{
count++;
}
}
but i got error so I was wondering if theres a good way to do it.
As the question is pretty unclear, I am assuming that you are looking for a pattern xox and want to know the position of o.
you can run a for loop and get the index.
to get the count of such patterns. you can increment the count by 1.
string str = "xxoxoxoxoxoxooxxxxox";
for(int i = 0; i < str.Length - 2; i++)
{
if (str[i] == 'x' && str[i +1] == 'o' && str[i+ 2] == 'x')
{
Console.WriteLine(i + 1);
count++;
}
}
you can change the character value based on your requirement.
you can use regex.matches to find all matches ...
string s = "xxoxoxoxoxoxooxxxxox";
Regex rx = new Regex("xox");
foreach (Match match in rx.Matches(s))
{
Console.WriteLine("Match index: "+ match.Index);
}
RegEx approach which gives you all indices of individual occupied seats oxo https://dotnetfiddle.net/3jc1Vq
string input = "xxoxoxoxoxoxooxxxxox";
// ^ ^ ^ ^ ^ ^
int[] indices = Regex.Matches(input, "(?<=x)o(?=x)").Cast<Match>().Select(x => x.Index).ToArray();
// in case you only want the count
int count = Regex.Matches(input, "(?<=x)o(?=x)").Count();
I made a working example that makes use of ReadOnlySpan<T> and avoids RegEx and over allocation.
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string seats = "xxoxoxoxoxoxooxxxxox";
var results = seats.ToCharArray().GetSingles('o');
foreach(var i in results)
{
Console.WriteLine(i);
}
}
}
public static class Ext
{
public static IReadOnlyList<int> GetSingles<T>(this T[] source, T search)
{
var results = new List<int>();
if(source.Length == 0)
{
return results;
}
if (source.Length == 1)
{
if (source[0].Equals(search))
{
results.Add(0);
}
return results;
}
if(source.Length >= 2)
{
if (source[0].Equals(search) && ! source[1].Equals(search))
{
results.Add(0);
}
if (source.Length == 2)
{
if (!source[0].Equals(search) && source[1].Equals(search))
{
results.Add(1);
}
return results;
}
}
ReadOnlySpan<T> window = new ReadOnlySpan<T>(source, 0, 3);
int i = 1;
for(; i < source.Length - 1; i++)
{
window = new ReadOnlySpan<T>(source, i - 1, 3);
if(!window[0].Equals(search) &&
window[1].Equals(search) &&
!window[2].Equals(search))
{
results.Add(i);
}
}
if(!window[1].Equals(search) && window[2].Equals(search))
{
results.Add(i + 1);
}
return results;
}
}
This outputs,
2
4
6
8
10
18
With the more challenging test data,
public class Program
{
public static void Main()
{
var tests = new string[]
{
"",
"o",
"x",
"oo",
"ox",
"xo",
"xx",
"oxx",
"oox",
"xox",
"xoo",
"xoxoxoxo",
"xoxoxoxoo",
"xoxoxox"
};
for(var i = 0; i < tests.Length; i++)
{
string seats = tests[i];
Console.WriteLine($"{i}:\"{seats}\"");
var results = seats.ToCharArray().GetSingles('o');
foreach(var r in results)
{
Console.WriteLine(r);
}
}
}
}
we get the correct output,
0:""
1:"o"
0
2:"x"
3:"oo"
4:"ox"
0
5:"xo"
1
6:"xx"
7:"oxx"
0
8:"oox"
9:"xox"
1
10:"xoo"
11:"xoxoxoxo"
1
3
5
8
12:"xoxoxoxoo"
1
3
5
13:"xoxoxox"
1
3
5

Parsing data from nested brackets in C#

Finally solved this myself after making many styles of parsers suffering from the same bug...
Working (cleaner but still needs more cleaning) code Here
if(input > 47 & input < 123) should be
if(input > 44 & input < 123) to include the '.'
thanks for no help.
Modifying This example code almost works for me, and is a starting point to learn more.
I've been trying to parse some files from the game Europa Universalis IV.
The files contain text like this:
Example 1
Example 2
In case someone wants to help debug Here is a browser version with 2 processed OuterEntities as example.
Once everything works the data would be put into a database after every object is finished. For testing I just write my progress to a text file.
I have tried this a couple times in different ways that almost always end up looking the same. By now the process is split into parts, and most of them work.
I start by collecting all the "OuterEntities" (First level brackets) in each of the GameFiles (just one for fast testing), this step is easy.
I put those outer entities into a list in a GameFile object (ToString overrides are just for testing) :
GameFile
internal record GameFile
{
public List<string> UnprocessedOuterEntites = new();
public string Name;
public string Path;
public List<OuterEntity> OuterEntities = new();
public override string ToString()
{
StringBuilder sb = new();
sb.AppendLine(Name);
sb.AppendLine(Path);
foreach(OuterEntity entity in OuterEntities)
{
sb.AppendLine(entity.ToString());
}
foreach(string entity in UnprocessedOuterEntites)
{
sb.AppendLine(entity);
}
return sb.ToString();
}
OuterEntity
internal class OuterEntity
{
public List<string> UnprocessedInnerEntities = new();
public string? Name = "";
public List<InnerEntity> InnerEntities = new();
public void Clear()
{
this.UnprocessedInnerEntities.Clear();
this.InnerEntities.Clear();
this.Name = null;
}
public override string ToString()
{
StringBuilder sb = new();
sb.Append(Name);
foreach (InnerEntity entity in InnerEntities)
{
sb.Append(entity.ToString());
}
foreach(string entity in UnprocessedInnerEntities)
{
sb.Append(entity);
}
return sb.ToString();
}
}
Those OuterEntities contain InnerEntities, which contain values or more InnerEntities (Nested brackets) :
Inner Entity
internal class InnerEntity
{
public List<string> UnprocessedInnerEntities = new();
public string? Name;
public string? Value;
public List<InnerEntity> InnerEntities = new();
public void Clear()
{
this.Name = null;
this.Value = null;
this.InnerEntities = new();
this.UnprocessedInnerEntities = new();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(Name);
if (InnerEntities.Count > 0)
{
foreach (InnerEntity entity in InnerEntities)
{
sb.Append(entity.ToString());
}
}
else
{
sb.AppendLine(Value);
}
foreach (string String in UnprocessedInnerEntities)
{
sb.AppendLine(String);
}
return sb.ToString();
}
The program is (for testing) run like this:
internal class Program{
private static Program program = new();
public List<GameFile> gameFiles = new();
public static void Main()
{
program.Run();
}
private void Run()
{
string[] paths = Directory.GetFiles("Source", "*.txt", SearchOption.AllDirectories);
foreach (string path in paths)
{
Process.GetOuterEntities(path,this);
}
Process.ProcessOuterEntities(this);
Process.ProcessInnerEntities(this);
Test.PrintOuterEntities(this);
}}
The OuterEntities are collected and processed:
public static void GetOuterEntities(string path, Program program)
{
string[] lines = System.IO.File.ReadAllLines(path);
GameFile file = new GameFile() { Path = path };
StringBuilder sb = new StringBuilder();
int currentPos = 0;
int lastPos = 0;
int brackets = 0;
bool inBrackets = false;
string st = RemoveComments(lines);
OuterEntity entity = new OuterEntity();
foreach (char c in st)
{
if (c == '{')
{
inBrackets = true;
brackets++;
}
else if (c == '}')
{
brackets--;
}
if (brackets == 0 && inBrackets)//End Outer
{
sb.Clear();
inBrackets = false;
for (int i = lastPos; i <= currentPos; i++)
{
if (st[i] != '\n')
{
sb.Append(st[i]);
}
}
file.UnprocessedOuterEntites.Add(sb.ToString());
program.gameFiles.Add(file);
lastPos = currentPos + 1;
}
currentPos++;
}
public static void ProcessOuterEntities(Program program)
{
foreach (GameFile file in program.gameFiles)
{
foreach (string UnprocessedOuterEntity in file.UnprocessedOuterEntites)
{
file.OuterEntities.Add(ProcessOuterEntity(UnprocessedOuterEntity));
}
file.UnprocessedOuterEntites.Clear();
}
}
private static OuterEntity ProcessOuterEntity(string UnprocessedOuterEntity)
{
OuterEntity processedOuterEntity = new();
int currentPos = 0;
int lastPos = 0;
int brackets = 0;
bool inBrackets = false;
StringBuilder sb = new StringBuilder();
foreach (char c in UnprocessedOuterEntity)
{
if (c == '{')
{
if (processedOuterEntity.Name == "")
{
for (int i = lastPos; i <= currentPos; i++)
{
if (UnprocessedOuterEntity[i] != '\n')
{
sb.Append(UnprocessedOuterEntity[i]);
}
}
processedOuterEntity.Name = sb.ToString();
sb.Clear();
lastPos = currentPos + 1;
}
inBrackets = true;
brackets++;
}
else if (c == '}')
{
brackets--;
}
if (brackets == 0 && inBrackets)
{
inBrackets = false;
for (int i = lastPos; i <= currentPos; i++)
{
sb.Append(UnprocessedOuterEntity[i]);
}
processedOuterEntity.UnprocessedInnerEntities.Add(sb.ToString());
sb.Clear();
lastPos = currentPos + 1;
}
currentPos++;
}
return processedOuterEntity;
}
After this I fail to process the inner entities.
This is the currently not working part:
private static InnerEntity ProcessInnerEntity(string UnprocessedInnerEntity, bool WaitingForValue = false)
{
InnerEntity processedInnerEntity = new();
int currentPos = 0;
int lastPos = 0;
int brackets = 0;
bool inBrackets = false;
bool waitingForValue = WaitingForValue;
StringBuilder sb = new StringBuilder();
foreach (char c in UnprocessedInnerEntity)
{
if (c == '{')//Brackets opening
{
inBrackets = true;
brackets++;
}
else if (c == '}')//Brackets closing
{
brackets--;
}
else if (c == '=')//Name behind, Value or NestedEntity in front
{
for (int i = lastPos; i <= currentPos; i++)
{
sb.Append(UnprocessedInnerEntity[i]);
}
processedInnerEntity.Name = sb.ToString();
sb.Clear();
lastPos = currentPos + 1;
waitingForValue = true;
if (inBrackets)//In a nested bracket, find InnerEntity
{
processedInnerEntity.InnerEntities.Add(ProcessInnerEntity(UnprocessedInnerEntity.Substring(currentPos + 1), waitingForValue));//Search everything in front
}
}
else if (c<47 | c > 123)//Not text
{
if (waitingForValue)//After =
{
for (int i = lastPos; i <= currentPos; i++)
{
if (c > 47 & c < 123)//Text
{
waitingForValue = false;
sb.Append(UnprocessedInnerEntity[i]);
}
}
if (!waitingForValue)//Has value
{
processedInnerEntity.Value = sb.ToString();
sb.Clear();
}
}
}
if (brackets == 0 && inBrackets)//Brackets closed
{
inBrackets = false;
currentPos++;
break;
}
currentPos++;
}
return processedInnerEntity;
}
The rest of the code can be found here
The debug file is written like this
internal class Test
{
public static void PrintOuterEntities(Program program)
{
List<string> strings = new();
foreach (GameFile gameFile in program.gameFiles)
{
strings.Add(gameFile.ToString());
}
foreach (string String in strings)
{
File.WriteAllText("test.txt", String);
}
}
}
Current output looks like this:
source\common\ideas\00_country_ideas.txt
HLR_ideas = { 1 diplomatic_reputation =
2 } bonus =
2 } bonus =
GER_ideas = { 0.3 infantry_power =
0.15 } bonus =
0.15 } bonus =
0.15 } bonus =
0.15 } bonus =
I want a list of OuterEntities containing their InnerEntities like this:
OuterEntity //Object
Name HLR_Ideas
InnerEntities //List
Name start
InnerEntities
Name possible_policy
Value 1
Name diplomatic_reputation
Value 2
Name bonus
InnerEntities
Name administrative_efficiency
Value 0.05
Name trigger
InnerEntities
Name tag
Value HLR
Name free
Value yes
Name hlr_imperial_throne
InnerEntities
Name legitimacy
Value 1.5
Name hlr_kaiserliche_armee
InnerEntities
Name land_morale
Value 0.15
Name hlr_imperial_diplomacy
InnerEntities
Name improve_relation_modifier
Value 0.33
Name hlr_centralised_empire
InnerEntities
Name global_tax_modifier
Value 0.2
Name hlr_roman_heritage
InnerEntities
Name core_creation
Value -0.2
Name hlr_adopting_the_goosestep
InnerEntities
Name discipline
Value 0.05
Name hlr_onwards_and_upwards
InnerEntities
Name governing_capacity_modifier
Value 0.1
Is there something obvious I'm doing wrong in the last part? Are there existing wheels I don't know about I'm trying to reinvent? Do I just learn Perl or the fancy non regular regular expressions I see out there?

Foreach won't return elements of char list

So im making this hangman game, as Im trying to learn C# but now im stuck with System.Collection.Generic.List'1[System.Char]. What im trying to do is to save wrong answers into List nepravilne, look into functions izpis and igra
class Program
{
static private int _sccore;
static void Main(string[] args)
{
string beseda;
int dolzina;
bool play=true;
char input;
do
{
beseda = izberi_besedo();
dolzina = beseda.Length;
igra(beseda, dolzina);
Console.WriteLine("Vnesite Y za nadaljevanje ali N za zakljucitev igre.");
input = char.Parse(Console.ReadLine());
if (input.Equals('y'))
{
play = true;
Console.WriteLine("play {0}",play);
}
if (input.Equals('n'))
{
play = false;
Console.WriteLine("play {0}", play);
}
} while (play == true);
}
static private string izberi_besedo() {
string[] besede = { "voda", "ladija", "letalo", "motor", "klavir", "harmonika", "saksofon", "oklep", "penkalo", "tiskalnik", "miza", "copat", "krogla", "klobuk", "gumb", "harfa", "kontrabas", "mandarina", "les", "knjiga", "vlak", "vijak", "struna", "kozarec" };
Random rnd = new Random();
int stevilka = rnd.Next(0, 23);
string beseda = besede[stevilka];
return beseda;
}
static private void igra (string beseda, int dolzina){
int i, poizkusi = 0;
int pravilne = 0;
bool endloop = false;
char crka;
List<char> nepravilne = new List<char>();//declaring char list for wrong words
string[] odkrite = new string[dolzina];
for(i=0; i<dolzina; i++) { odkrite[i] = "_"; }
do {
izpis(odkrite,nepravilne); //izpis - function which returns just text, we are inputing list nepravilne, which are wrong answers
vpis(out crka);
if (!(beseda.Contains(crka)))//if word doesen't contain letter
{
poizkusi++;
_sccore--;
nepravilne.Add(crka);//add that letter to list
}
for (i = 0; i<dolzina; i++)
{
if (crka.Equals(beseda[i]))
{
odkrite[i] = Convert.ToString(crka);
pravilne++;
_sccore++;
}
}
Console.Clear();
if (pravilne >= dolzina || poizkusi >= 4)endloop = true;
} while (endloop==false);
}
static private void vpis(out char crka)
{
string vpis;
bool stevilka=false, status;
Console.WriteLine("\nVnesite crko za ugibanje besede");
vpis = Console.ReadLine();
stevilka = IsNumeric(vpis);
if (vpis.Length == 1 && stevilka==false)
{
crka = Convert.ToChar(vpis);
}
else
{
do
{
status = false;
if (vpis.Length!=1) Console.WriteLine("Vnesli ste prevec crk, poizkusite ponovno");
if(stevilka==true) Console.WriteLine("Vnesli ste stevilko, poizkusite ponovno");
vpis = Console.ReadLine();
stevilka = IsNumeric(vpis);
if (vpis.Length == 1 && stevilka == false)
{
status = true;
}
} while (status==false);
crka = Convert.ToChar(vpis);
}
}
private static bool IsNumeric(string vpis)
{
int number;
return int.TryParse(vpis, out number);
}
private static void izpis(string[] odkrite, List<char> nepravilne)
{
Console.Write("Rezultat {0} | ", _sccore);
foreach (char element in nepravilne)//write out char elements which contain letter
{
Console.Write("{0} ", nepravilne);
}
Console.WriteLine();
foreach (string element in odkrite)
{
Console.Write("{0} ", element);
}
}
}
}
I think you have a typo in the following code, i.e I think you are intending to print the variable element in the loop and not nepravilne:
foreach (char element in nepravilne)
{
Console.Write("{0} ", nepravilne);
}
Should be as follows instead?
foreach (char element in nepravilne)
{
Console.Write("{0} ", element);
}

Check if a string is a palindrome

I have a string as input and have to break the string in two substrings. If the left substring equals the right substring then do some logic.
How can I do this?
Sample:
public bool getStatus(string myString)
{
}
Example: myString = "ankYkna", so if we break it into two substring it would be:
left-part = "ank",
right-part = "ank" (after reversal).
Just for fun:
return myString.SequenceEqual(myString.Reverse());
public static bool getStatus(string myString)
{
string first = myString.Substring(0, myString.Length / 2);
char[] arr = myString.ToCharArray();
Array.Reverse(arr);
string temp = new string(arr);
string second = temp.Substring(0, temp.Length / 2);
return first.Equals(second);
}
int length = myString.Length;
for (int i = 0; i < length / 2; i++)
{
if (myString[i] != myString[length - i - 1])
return false;
}
return true;
Using LINQ and off course far from the best solution
var original = "ankYkna";
var reversed = new string(original.Reverse().ToArray());
var palindrom = original == reversed;
A single line of code using Linq
public static bool IsPalindrome(string str)
{
return str.SequenceEqual(str.Reverse());
}
public static bool IsPalindrome(string value)
{
int i = 0;
int j = value.Length - 1;
while (true)
{
if (i > j)
{
return true;
}
char a = value[i];
char b = value[j];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
i++;
j--;
}
}
//This c# method will check for even and odd lengh palindrome string
public static bool IsPalenDrome(string palendromeString)
{
bool isPalenDrome = false;
try
{
int halfLength = palendromeString.Length / 2;
string leftHalfString = palendromeString.Substring(0,halfLength);
char[] reversedArray = palendromeString.ToCharArray();
Array.Reverse(reversedArray);
string reversedString = new string(reversedArray);
string rightHalfStringReversed = reversedString.Substring(0, halfLength);
isPalenDrome = leftHalfString == rightHalfStringReversed ? true : false;
}
catch (Exception ex)
{
throw ex;
}
return isPalenDrome;
}
In C# :
public bool EhPalindromo(string text)
{
var reverseText = string.Join("", text.ToLower().Reverse());
return reverseText == text;
}
This is a short and efficient way of checking palindrome.
bool checkPalindrome(string inputString) {
int length = inputString.Length;
for(int i = 0; i < length/2; i++){
if(inputString[i] != inputString[length-1-i]){
return false;
}
}
return true;
}
This way is both concise in appearance & processes very quickly.
Func<string, bool> IsPalindrome = s => s.Reverse().Equals(s);
public static bool IsPalindrome(string word)
{
//first reverse the string
string reversedString = new string(word.Reverse().ToArray());
return string.Compare(word, reversedString) == 0 ? true : false;
}
Out of all the solutions, below can also be tried:
public static bool IsPalindrome(string s)
{
return s == new string(s.Reverse().ToArray());
}
String extension method, easy to use:
public static bool IsPalindrome(this string str)
{
str = new Regex("[^a-zA-Z]").Replace(str, "").ToLower();
return !str.Where((t, i) => t != str[str.Length - i - 1]).Any();
}
private void CheckIfPalindrome(string str)
{
//place string in array of chars
char[] array = str.ToCharArray();
int length = array.Length -1 ;
Boolean palindrome =true;
for (int i = 0; i <= length; i++)//go through the array
{
if (array[i] != array[length])//compare if the char in the same positions are the same eg "tattarrattat" will compare array[0]=t with array[11] =t if are not the same stop the for loop
{
MessageBox.Show("not");
palindrome = false;
break;
}
else //if they are the same make length smaller by one and do the same
{
length--;
}
}
if (palindrome) MessageBox.Show("Palindrome");
}
use this way from dotnetperls
using System;
class Program
{
/// <summary>
/// Determines whether the string is a palindrome.
/// </summary>
public static bool IsPalindrome(string value)
{
int min = 0;
int max = value.Length - 1;
while (true)
{
if (min > max)
{
return true;
}
char a = value[min];
char b = value[max];
// Scan forward for a while invalid.
while (!char.IsLetterOrDigit(a))
{
min++;
if (min > max)
{
return true;
}
a = value[min];
}
// Scan backward for b while invalid.
while (!char.IsLetterOrDigit(b))
{
max--;
if (min > max)
{
return true;
}
b = value[max];
}
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
min++;
max--;
}
}
static void Main()
{
string[] array =
{
"A man, a plan, a canal: Panama.",
"A Toyota. Race fast, safe car. A Toyota.",
"Cigar? Toss it in a can. It is so tragic.",
"Dammit, I'm mad!",
"Delia saw I was ailed.",
"Desserts, I stressed!",
"Draw, O coward!",
"Lepers repel.",
"Live not on evil.",
"Lonely Tylenol.",
"Murder for a jar of red rum.",
"Never odd or even.",
"No lemon, no melon.",
"Senile felines.",
"So many dynamos!",
"Step on no pets.",
"Was it a car or a cat I saw?",
"Dot Net Perls is not a palindrome.",
"Why are you reading this?",
"This article is not useful.",
"...",
"...Test"
};
foreach (string value in array)
{
Console.WriteLine("{0} = {1}", value, IsPalindrome(value));
}
}
}
If you just need to detect a palindrome, you can do it with a regex, as explained here. Probably not the most efficient approach, though...
That is non-trivial, there is no built in method to do that for you, you'll have to write your own. You will need to consider what rules you would like to check, like you implicitly stated you accepted reversing of one string. Also, you missed out the middle character, is this only if odd length?
So you will have something like:
if(myString.length % 2 = 0)
{
//even
string a = myString.substring(0, myString.length / 2);
string b = myString.substring(myString.length / 2 + 1, myString.lenght/2);
if(a == b)
return true;
//Rule 1: reverse
if(a == b.reverse()) //can't remember if this is a method, if not you'll have to write that too
return true;
etc, also doing whatever you want for odd strings
This C# method will check for even and odd length palindrome string (Recursive Approach):
public static bool IsPalindromeResursive(int rightIndex, int leftIndex, char[] inputString)
{
if (rightIndex == leftIndex || rightIndex < leftIndex)
return true;
if (inputString[rightIndex] == inputString[leftIndex])
return IsPalindromeResursive(--rightIndex, ++leftIndex, inputString);
else
return false;
}
public Boolean IsPalindrome(string value)
{
var one = value.ToList<char>();
var two = one.Reverse<char>().ToList();
return one.Equals(two);
}
class Program
{
static void Main(string[] args)
{
string s, revs = "";
Console.WriteLine(" Enter string");
s = Console.ReadLine();
for (int i = s.Length - 1; i >= 0; i--) //String Reverse
{
Console.WriteLine(i);
revs += s[i].ToString();
}
if (revs == s) // Checking whether string is palindrome or not
{
Console.WriteLine("String is Palindrome");
}
else
{
Console.WriteLine("String is not Palindrome");
}
Console.ReadKey();
}
}
public bool IsPalindroom(string input)
{
input = input.ToLower();
var loops = input.Length / 2;
var higherBoundIdx = input.Length - 1;
for (var lowerBoundIdx = 0; lowerBoundIdx < loops; lowerBoundIdx++, higherBoundIdx--)
{
if (input[lowerBoundIdx] != input[higherBoundIdx])
return false;
}
return true;
}
Here is an absolutely simple way to do this,
Receive the word as input into a method.
Assign a temp variable to the original value.
Loop through the initial word, and add the last character to the reversal that you are constructing until the inital word has no more characters.
Now use the spare you created to hold the original value to compare to the constructed copy.
This is a nice way as u don't have to cast ints and doubles. U can just pass them to the method in their string representation by using the ToString() method.
public static bool IsPalindrome(string word)
{
string spare = word;
string reversal = null;
while (word.Length > 0)
{
reversal = string.Concat(reversal, word.LastOrDefault());
word = word.Remove(word.Length - 1);
}
return spare.Equals(reversal);
}
So from your main method,
For even and odd length strings u just pass the whole string into the method.
Since a palindrome also includes numbers, words, sentences, and any combinations of these, and should ignore punctuation and case, (See Wikipedia Article)
I propose this solution:
public class Palindrome
{
static IList<int> Allowed = new List<int> {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'1', '2', '3', '4', '5', '6', '7', '8', '9',
'0'
};
private static int[] GetJustAllowed(string text)
{
List<int> characters = new List<int>();
foreach (var c in text)
characters.Add(c | 0x20);
return characters.Where(c => Allowed.Contains(c)).ToArray();
}
public static bool IsPalindrome(string text)
{
if(text == null || text.Length == 1)
return true;
int[] chars = GetJustAllowed(text);
var length = chars.Length;
while (length > 0)
if (chars[chars.Length - length] != chars[--length])
return false;
return true;
}
public static bool IsPalindrome(int number)
{
return IsPalindrome(number.ToString());
}
public static bool IsPalindrome(double number)
{
return IsPalindrome(number.ToString());
}
public static bool IsPalindrome(decimal number)
{
return IsPalindrome(number.ToString());
}
}
static void Main(string[] args)
{
string str, rev="";
Console.Write("Enter string");
str = Console.ReadLine();
for (int i = str.Length - 1; i >= 0; i--)
{
rev = rev + str[i];
}
if (rev == str)
Console.Write("Entered string is pallindrome");
else
Console.Write("Entered string is not pallindrome");
Console.ReadKey();
}
string test = "Malayalam";
char[] palindrome = test.ToCharArray();
char[] reversestring = new char[palindrome.Count()];
for (int i = palindrome.Count() - 1; i >= 0; i--)
{
reversestring[palindrome.Count() - 1 - i] = palindrome[i];
}
string materializedString = new string(reversestring);
if (materializedString.ToLower() == test.ToLower())
{
Console.Write("Palindrome!");
}
else
{
Console.Write("Not a Palindrome!");
}
Console.Read();
public static bool palindrome(string t)
{
int i = t.Length;
for (int j = 0; j < i / 2; j++)
{
if (t[j] == t[i - j-1])
{
continue;
}
else
{
return false;
break;
}
}
return true;
}
public bool Solution(string content)
{
int length = content.Length;
int half = length/2;
int isOddLength = length%2;
// Counter for checking the string from the middle
int j = (isOddLength==0) ? half:half+1;
for(int i=half-1;i>=0;i--)
{
if(content[i] != content[j])
{
return false;
}
j++;
}
return true;
}
public bool MojTestPalindrome (string word)
{
bool yes = false;
char[]test1 = word.ToArray();
char[] test2 = test1.Reverse().ToArray();
for (int i=0; i< test2.Length; i++)
{
if (test1[i] != test2[test2.Length - 1 - i])
{
yes = false;
break;
}
else {
yes = true;
}
}
if (yes == true)
{
return true;
}
else
return false;
}
public static bool IsPalindrome(string str)
{
int i = 0;
int a = 0;
char[] chr = str.ToCharArray();
foreach (char cr in chr)
{
Array.Reverse(chr);
if (chr[i] == cr)
{
if (a == str.Length)
{
return true;
}
a++;
i++;
}
else
{
return false;
}
}
return true;
}
The various provided answers are wrong for numerous reasons, primarily from misunderstanding what a palindrome is. The majority only properly identify a subset of palindromes.
From Merriam-Webster
A word, verse, or sentence (such as "Able was I ere I saw Elba")
And from Wordnik
A word, phrase, verse, or sentence that reads the same backward or forward. For example: A man, a plan, a canal, Panama!
Consider non-trivial palindromes such as "Malayalam" (it's a proper language, so naming rules apply, and it should be capitalized), or palindromic sentences such as "Was it a car or a cat I saw?" or "No 'X' in Nixon".
These are recognized palindromes in any literature.
I'm lifting the thorough solution from a library providing this kind of stuff that I'm the primary author of, so the solution works for both String and ReadOnlySpan<Char> because that's a requirement I've imposed on the library. The solution for purely String will be easy to determine from this, however.
public static Boolean IsPalindrome(this String #string) =>
!(#string is null) && #string.AsSpan().IsPalindrome();
public static Boolean IsPalindrome(this ReadOnlySpan<Char> span) {
// First we need to build the string without any punctuation or whitespace or any other
// unrelated-to-reading characters.
StringBuilder builder = new StringBuilder(span.Length);
foreach (Char s in span) {
if (!(s.IsControl()
|| s.IsPunctuation()
|| s.IsSeparator()
|| s.IsWhiteSpace()) {
_ = builder.Append(s);
}
}
String prepped = builder.ToString();
String reversed = prepped.Reverse().Join();
// Now actually check it's a palindrome
return String.Equals(prepped, reversed, StringComparison.CurrentCultureIgnoreCase);
}
You're going to want variants of this that accept a CultureInfo parameter as well, when you're testing a specific language rather than your own language, by instead calling .ToUpper(cultureInfo) on prepped.
And here's proof from the projects unit tests that it works.

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