您的位置:首页 > 编程语言 > C语言/C++

字符串处理问题(c++和c#两种解法)

2011-10-15 22:15 489 查看


c++解法:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string str1,characters,numbers;
int count,first,last;
char temp;
while(cin>>str1&&str1!="**")
{
count=str1.length();
first=0;last=count;
char *p=new char[count];
for(int i=0;i<count;i++)
{
if(str1[i]>='0'&&str1[i]<='9')
{
p[first]=str1[i];
first++;
}
if(str1[i]>='a'&&str1[i]<='z')
{
p[last]=str1[i]-32;
last--;
}
if(str1[i]>='A'&&str1[i]<='Z')
{
p[last]=str1[i];
last--;
}
}
if(first==0)
cout<<"There are not digits";
else
{
sort(p,p+first);
for(int i=0;i<first;i++)
cout<<p[i];
}
if(last==count)
cout<<"\n"<<"There are not letters"<<"\n";
else
{
cout<<"\n";
sort(p+last+1,p+count+1);//此处应注意last指针的位置
for(int i=last+1;i<=count;i++)
cout<<p[i];
cout<<"\n";
}

}
return 0;
}

c#解法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ceshi
{
class Program
{
public static string s;
static bool di = false, le = false;
public static char[] digits = new char[80];
public static char[] letters = new char[80];
static void Main(string[] args)
{
s = Console.ReadLine();
for (int i = 0; i < 80; i++)
{
digits[i] = '#';
letters[i] = '#';
}
if (s != "**")
{
string s1 = s.ToUpper();//先将字符串中的所有小写字母转换成大写
for (int i = 0; i < s.Length; i++)
{
if (s1[i] >= '0' && s1[i] <= '9')//字符串带下标相等于char
{
digits[i] = s1[i];
di = true;
}
if (s1[i] >= 'A' && s1[i] <= 'Z')//最初模仿c++中的方法将a通过a-32换成A,但在c#中letters[i]=s1[i]-32不可以直接赋值,因此只好在开头通过ToUpper()将小写全部转换为大写,然后直接将大写字母填充到letters中。
{
letters[i] = s1[i];
le = true;
}
}
if (!di)
Console.Write("There are not digits.");
else
{
Array.Sort(digits);//排序算法,升序(另有方法array.reverse为降序)
for (int i = 0; i < 80; i++)
{
if (digits[i] != '#')
Console.Write(digits[i]);
}
}
if (!le)
Console.WriteLine("There are not letters.");
else
{
Console.WriteLine();
Array.Sort(letters);
for (int i = 0; i < 80; i++)
{
if (letters[i] != '#')
Console.Write(letters[i]);
}
Console.WriteLine();
}
}
Console.Read();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐