黑马程序员技术交流社区
标题:
怎么样把字符串中重复符号去掉?
[打印本页]
作者:
jy郑娟
时间:
2013-3-15 09:48
标题:
怎么样把字符串中重复符号去掉?
怎么样把字符串中重复符号去掉?比如说1234561123sfsd----得到的是123456sfd-
作者:
android2050
时间:
2013-3-15 10:34
package com.datoucth;
public class Test {
public static int removeDuplicateChar(char []str){
int len = str.length;
if(len < 2) return len;
for(int i=0;i<len-1;i++){
char ch = str[i];
int index = i+1;
for(int j=i+1;j<=len-1;){
if(ch == str[j]){
j++;
}else {
if(j!=index){
str[index] = str[j];
}
j++; index++;
}
}
len = index;
}
return len;
}
public static void test(char []str){
int len = removeDuplicateChar(str);
for(int i=0;i<len;i++){
System.out.print(str[i]);
}
System.out.println();
}
public static void main(String[] args) {
String str = "1234561123sfsd";
test(str.toCharArray());
}
}
复制代码
作者:
朱传波
时间:
2013-3-15 11:22
本帖最后由 朱传波 于 2013-3-15 12:00 编辑
namespace 改变子字符串
{
class Program
{
static void Main(string[] args)
{
//将字符串的重复字符去掉
string str = "1234561123sfsd";
char [] cha = str.ToCharArray();//将字符串转化为char数组
//通过两层for循环寻找cha数组中是否有一致的字符
for (int i = 0; i < cha.Length; i++)
{
for (int j = 0; j < i; j++)
{
if (cha[j] == cha[i])
{
cha[i]='!';//用‘!’标记一致的字符
}
}
}
string str2 = new string(cha);//将标记后的char数组重新转换为字符串
char[] remove={'!'};
string[] result = str2.Split(remove [],StringSplitOptions.RemoveEmptyEntries);//剔除!,然后再输出结果
Console.Write(result );
Console.ReadKey();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2