我有一个字符串作为输入,并且必须将字符串分成两个子字符串。如果左子字符串等于右子字符串,则执行一些逻辑。
我怎样才能做到这一点?
样本:
public bool getStatus(string myString)
{
}
示例:myString = "ankYkna"
,因此如果我们将其分成两个子字符串,它将是:
left-part = "ank"
,
right-part = "ank"
(反转后)。
我有一个字符串作为输入,并且必须将字符串分成两个子字符串。如果左子字符串等于右子字符串,则执行一些逻辑。
我怎样才能做到这一点?
样本:
public bool getStatus(string myString)
{
}
示例:myString = "ankYkna"
,因此如果我们将其分成两个子字符串,它将是:
left-part = "ank"
,
right-part = "ank"
(反转后)。
只是为了好玩:
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;
使用 LINQ,当然远非最佳解决方案
var original = "ankYkna";
var reversed = new string(original.Reverse().ToArray());
var palindrom = original == reversed;
一行代码使用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--;
}
}
//这个c#方法将检查偶数和奇数长度的回文字符串
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;
}
这种方式外观简洁,处理速度非常快。
Func<string, bool> IsPalindrome = s => s.Reverse().Equals(s);
在 C# 中:
public bool EhPalindromo(string text)
{
var reverseText = string.Join("", text.ToLower().Reverse());
return reverseText == text;
}
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;
}
字符串扩展方法,简单易用:
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");
}
从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));
}
}
}
这是检查回文的一种简短而有效的方法。
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;
}
如果您只需要检测回文,您可以使用正则表达式来完成,如此处所述。可能不是最有效的方法,虽然......
这很重要,没有内置的方法可以为您做到这一点,您必须自己编写。您将需要考虑要检查哪些规则,就像您暗示您接受一个字符串的反转一样。另外,您错过了中间字符,这仅是奇数吗?
所以你会有类似的东西:
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;
等等,也可以为奇数字符串做任何你想做的事情
此 C# 方法将检查偶数和奇数长度的回文字符串(递归方法):
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;
}
由于回文还包括数字、单词、句子以及它们的任何组合,并且应该忽略标点符号和大小写,(参见维基百科文章)我提出了这个解决方案:
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());
}
}
这是一个绝对简单的方法,
这是一个不错的方法,因为您不必强制转换整数和双打。您可以使用 ToString() 方法将它们传递给字符串表示形式的方法。
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);
}
因此,从您的主要方法中,对于偶数和奇数长度的字符串,您只需将整个字符串传递给该方法。
在所有解决方案中,也可以尝试以下方法:
public static bool IsPalindrome(string s)
{
return s == new string(s.Reverse().ToArray());
}
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;
}
由于多种原因,提供的各种答案都是错误的,主要是由于误解了回文是什么。大多数只正确识别回文的子集。
来自韦氏词典
一个词、诗句或句子(例如“我在看到厄尔巴岛之前能够做到”)
来自 Wordnik
向后或向前读相同的单词、短语、诗句或句子。例如:一个人,一个计划,一条运河,巴拿马!
考虑不平凡的回文,例如“马拉雅拉姆语”(这是一种适当的语言,因此适用命名规则,并且应该大写),或回文句子,例如“我看到的是汽车还是猫?” 或“尼克松没有'X'”。
这些在任何文献中都是公认的回文。
我正在从一个提供我是主要作者的这类东西的库中提取彻底的解决方案,因此该解决方案适用于两者String
,ReadOnlySpan<Char>
因为这是我对库强加的要求。但是,pure 的解决方案String
很容易从中确定。
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);
}
CultureInfo
当您通过调用.ToUpper(cultureInfo)
.prepped
这是来自项目单元测试的证明,它可以工作。
static void Main(string[] args)
{
Console.WriteLine("Enter a string to check pallingdrome i.e startreverse is same");
string str = Convert.ToString( Console.ReadLine());
char[] arr = str.ToCharArray();
var strLength = arr.Length-1;
string newStr = "";
for (var i= strLength; i < arr.Length; i--)
{
newStr = newStr + Convert.ToString(arr[i]);
if(i==0)
{
break;
}
}
if(str==newStr)
{
Console.WriteLine("Entered key is Palindrome");
Console.ReadLine();
}
else
{
Console.WriteLine("Entered key is not Palindrome");
Console.ReadLine();
}
}
使用传统方法找到回文的最短技术
public string IsPalindrome(string Word)
{
int i = 0, j = Word.Length - 1;
for (; i < Word.Length - 1 && j >= 0 && Word[i] == Word[j]; i++, j--) ;
return j == 0 ? "Palindrome" : "Not Palindrome";
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class palindrome
{
static void Main(string[] args)
{
Console.Write("Enter a number:");
string panstring = Console.ReadLine();
Palindrome(panstring);
Console.ReadKey();
}
static int index = 0;
public static void Palindrome(string strexcluding)
{
try
{
string reversecounter = string.Empty;
for (int i = strexcluding.Length - 1; i >= 0; i--)
{
if (strexcluding[i].ToString() != null)
reversecounter += strexcluding[i].ToString();
}
if (reversecounter == strexcluding)
{
Console.WriteLine("Palindrome Number: " + strexcluding);
}
else
{
Sum(strexcluding);
}
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public static void Sum(string stringnumber)
{
try
{
index++;
string number1 = stringnumber;
string number2 = stringnumber;
string[] array = new string[number1.Length];
string obtained = string.Empty;
string sreverse = null;
Console.WriteLine(index + ".step : " + number1 + "+" + number2);
for (int i = 0; i < number1.Length; i++)
{
int temp1 = Convert.ToInt32(number1[number1.Length - i - 1].ToString());
int temp2 = Convert.ToInt32(number2[number2.Length - i - 1].ToString());
if (temp1 + temp2 >= 10)
{
if (number1.Length - 1 == number1.Length - 1 - i)
{
array[i] = ((temp1 + temp2) - 10).ToString();
obtained = "one";
}
else if (number1.Length - 1 == i)
{
if (obtained == "one")
{
array[i] = (temp1 + temp2 + 1).ToString();
}
else
{
array[i] = (temp1 + temp2).ToString();
}
}
else
{
if (obtained == "one")
{
array[i] = ((temp1 + temp2 + 1) - 10).ToString();
}
else
{
array[i] = ((temp1 + temp2) - 10).ToString();
obtained = "one";
}
}
}
else
{
if (obtained == "one")
array[i] = (temp1 + temp2 + 1).ToString();
else
array[i] = (temp1 + temp2).ToString();
obtained = "Zero";
}
}
for (int i = array.Length - 1; i >= 0; i--)
{
if (array[i] != null)
sreverse += array[i].ToString();
}
Palindrome(sreverse);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}